[R] How to read many files at one time?

Mike Lawrence Mike.Lawrence at DAL.CA
Sat Jul 14 23:51:59 CEST 2007


On 14-Jul-07, at 6:16 PM, Zhang Jian wrote:

> I want to load many files in the R. The names of the files are  
> "Sim1.txt", "
> Sim2.txt", "Sim3.txt", "Sim4.txt", "Sim5.txt" and so on.
> Can I read them at one time? What should I do? I can give the same  
> names in
> R.
> Thanks.
>
> For example:
>> tst=paste("Sim",1:20,".txt",sep="") # the file names
>> tst
>  [1] "Sim1.txt"  "Sim2.txt"  "Sim3.txt"  "Sim4.txt"  "Sim5.txt"   
> "Sim6.txt"
>  [7] "Sim7.txt"  "Sim8.txt"  "Sim9.txt"  "Sim10.txt" "Sim11.txt"  
> "Sim12.txt"
> [13] "Sim13.txt" "Sim14.txt" "Sim15.txt" "Sim16.txt" "Sim17.txt"  
> "Sim18.txt"
> [19] "Sim19.txt" "Sim20.txt"
>
>> data.name=paste("Sim",1:20,sep="") # the file names in R
>> data.name
>  [1] "Sim1"  "Sim2"  "Sim3"  "Sim4"  "Sim5"  "Sim6"  "Sim7"   
> "Sim8"  "Sim9"
> [10] "Sim10" "Sim11" "Sim12" "Sim13" "Sim14" "Sim15" "Sim16"  
> "Sim17" "Sim18"
> [19] "Sim19" "Sim20"

you could read each data file as a named element into a single list
data=list(NULL)
for(i in 1:length(tst)){
	data[[i]]=read.table(tst[i])
	names(data)[i]=data.name[i]
}

if you want to refer to Sim1, type
data$"Sim1"



More information about the R-help mailing list