Skip to content
Prev 333373 / 398506 Next

How to extract sets of rows (not sorted) from text file in R, do some methods on these rows, save the result in another text file, then pick others set of rows and do the same

Hi,
You may need ?split(), or ?aggregate() or ?ddply() from library(plyr)

dat1 <- read.table(tex="1 2 4 7 8 9
1 4 5 8 9
1 4 5 6 9
2 3 4 8
3 6 7 8
1 5 6 9
2 5 7 9",header=FALSE,sep="",fill=TRUE)?
##

?res1 <- do.call(rbind,lapply(split(dat1,dat1[,1]),function(x) c(V1=x[1,1],colSums(x[,-1],na.rm=TRUE))))
?write.table(res1,file="new.txt",row.names=FALSE,quote=FALSE)

#or
res2 <- with(dat1,aggregate(cbind(V2,V3,V4,V5,V6),list(V1=V1),sum,na.rm=TRUE))


#or
library(plyr)
res3 <- ddply(dat1,.(V1),colwise(sum,na.rm=TRUE))

A.K.


Hi, 
in a text file like 
1 2 4 7 8 9 
1 4 5 8 9 
1 4 5 6 9 
2 3 4 8 
3 6 7 8 
1 5 6 9 
2 5 7 9 
And so on 

where the first column represents group's number 

data <- read.table("in.txt") 

## first: 
? ? ? ?- select rows that strat with one (check first column), apply
methods only on thes rows (expect for the first column in each line); 

? ? ? ?- save the result in another text file namely new.txt 

## second: 
? ? ? ?- do the same for these rows start with with two 

? ? ? ?- save the result in new.txt after the prevous result 
And so on 


I have 9000 lines and around 100 groups (first column). 



for (i in 1:9000 ) { 

newdata <- data[ , which(data$V1 =='1')] 

- apply methods 
- save the result 
} 


Thanks for any help
Message-ID: <1384875241.25223.YahooMailNeo@web142601.mail.bf1.yahoo.com>
In-Reply-To: <1384872404.30392.YahooMailNeo@web142604.mail.bf1.yahoo.com>