[R] Open multiple files using a loop

arun smartpink111 at yahoo.com
Fri Dec 6 19:01:33 CET 2013


Hi Chris,

May be this helps.

#Suppose the working directory is `FirstLevel`
D <- dir(recursive=TRUE)
 D
#[1] "S1/S1data.txt" "S2/S2data.txt" "S3/S3data.txt"
sapply(D,function(x) nrow(read.table(x,sep="",header=TRUE)))
#S1/S1data.txt S2/S2data.txt S3/S3data.txt 
#           20            20            20 

res <- do.call(rbind,lapply(D,function(x) read.table(x,sep="",header=TRUE)))
 dim(res)
#[1] 60  2
A.K.


Dear R/Arun 

I would like to open 50 text different files (S1data; S2data; 
S3data etc.) and rbind() them into a single data.frame or matrix. Is 
there a way doing this with a loop or in some other time-saving manner? 

`S1data` <- read.table("~/fmridata/FirstLevel/S1/S1data", header=T, quote="\"") 
`S2data` <- read.table("~/fmridata/FirstLevel/S2/S2data", header=T, quote="\"") 
`S3data` <- read.table("~/fmridata/FirstLevel/S3/S3data", header=T, quote="\"") 

etc… to S50 

alldata <- rbind(S1data, S2data, S3data etc… to 50) 


This type of idea (assuming each file has 10 rows (x50=500) and 25 columns): 

subjects <- c(S1,S2,S3 etc… to S50) 
alldata <- matrix(nrow = 500, ncol=25, byrow=TRUE) 

for(i in 1:50) { 
`<subject[i]>data` <- read.table("~/fmridata/FirstLevel/(subject[i])/<subject[i]>data", header=T, quote="\"") 

alldata[i,] <- <subject[i]>data 

} 

Thanks, 
Chris



More information about the R-help mailing list