[R] Exporting columns into multiple files - loop query

WOOD, Matthew mjwood at glos.ac.uk
Sat Mar 26 03:45:44 CET 2011


Hi,

I'm using a loop to extract 2 columns from an array into multiple files. 
I can use the following to export 3 files, containing column 'ID' with one of
the three event columns.

> ID<-c("A","B","C","D","E","F")
> event1<-c(0,1,0,0,1,0)
> event2<-c(1,1,0,1,0,0)
> event3<-c(1,0,1,0,1,0)
> data<-cbind(ID,event1,event2,event3)
> data
     ID  event1 event2 event3
[1,] "A" "0"    "1"    "1"   
[2,] "B" "1"    "1"    "0"   
[3,] "C" "0"    "0"    "1"   
[4,] "D" "0"    "1"    "0"   
[5,] "E" "1"    "0"    "1"   
[6,] "F" "0"    "0"    "0"   

The data represent individuals that are either seen (1) or not seen (0) on
several occasions.
> 
> n<-ncol(data)
> 
> for(i in 2:n) {
+ df<-data.frame(data[,i],ID) 
+ myfile<-gsub("( )", "",paste(i,".txt")) # name file by year 
+ write.table(df, file=myfile,
sep="\t",row.names=F,col.names=F,quote=FALSE,append=FALSE) 
+ }  

My question: How can I add a function to this loop, to delete rows in the
data frame in which the event is equal to zero? 

An desired file output would be:
     ID  event2
[1,] "A" "1"      
[2,] "B" "1"      
[3,] "D" "1"   

I can handle this taking each file separately using subscripts, but my
attempts to amend the loop, and be able to run this code on a bunch of large
mutliple event files, have failed.

With grateful thanks in advance,

Matt

--
Matt Wood
Department of Natural and Social Sciences
University of Gloucestershire
Francis Close Hall
Cheltenham 
GL50 4AZ



'In the top three in the People and Planet green league table; committed to sustainability'

This email is confidential to the intended recipient. If you have received it in error please notify the sender and delete it from your computer.

The University of Gloucestershire is a company limited by guarantee registered in England and Wales. Registered number: 06023243 Registered office: The Park, Cheltenham, GL50 2RH

Please consider the environment before printing this email.



More information about the R-help mailing list