r - Repeating the same command for x number of times -
this question has answer here:
i trying repeat same command x number of times, simple example read files same names different years 10 times, can this
yr2001detail<-read.csv("e:/yr2001detail.csv",stringsasfactors = false,header=true ) yr2002detail<-read.csv("e:/yr2002detail.csv",stringsasfactors = false,header=true ) yr2003detail<-read.csv("e:/yr2003detail.csv",stringsasfactors = false,header=true ) yr2004detail<-read.csv("e:/yr2004detail.csv",stringsasfactors = false,header=true ) yr2005detail<-read.csv("e:/yr2005detail.csv",stringsasfactors = false,header=true ) yr2006detail<-read.csv("e:/yr2006detail.csv",stringsasfactors = false,header=true ) yr2007detail<-read.csv("e:/yr2007detail.csv",stringsasfactors = false,header=true ) yr2008detail<-read.csv("e:/yr2008detail.csv",stringsasfactors = false,header=true ) yr2009detail<-read.csv("e:/yr2009detail.csv",stringsasfactors = false,header=true ) yr2010detail<-read.csv("e:/yr2010detail.csv",stringsasfactors = false,header=true )
which bad, because i'm repeating myself , time consuming if there way many files or if have repeat many times. have tried exploring doing
for(i in 1:10){ paste("yr",2000+i,"detail",sep="")<-read.csv(paste("e:/yr",2000+i,"detail.csv",sep=""),stringsasfactors = false,header=true ) }
which didnt work because of left side, , this
vector <- rep(na,10) for(i in 1:10){ vector[i] <- paste("yr",2000+i,"detail",sep="") } for(i in 1:10){ vector[i]<-read.csv(paste("e:/yr",2000+i,"detail.csv",sep=""),stringsasfactors = false,header=true ) }
i asking further down along way, i'll have deal data yearly means assigning more repetitive commands each year.
we can use sprintf
create 'files' , 'filenames'
files <- sprintf("e:/yr%ddetail.csv", 2001:2010) filenames <- sprintf("yr%ddetail", 2001:2010)
or paste
can used
files <- paste0("e:/", 2001:2010, "detail.csv") filenames <- paste0("yr", 2001:2010, "detail")
and loop through files read it. if need separate objects, use assign
,
for(j in seq_along(filenames)){ assign(filenames[j], read.csv(files[j], stringsasfactors=false, header=true)) }
however, better read in list
rather having many objects in global environment, i.e.
lst <- setnames(lapply(files, read.csv, stringsasfactors=false, header=true), filenames)
or faster option fread
library(data.table) lst <- setnames(lapply(files, fread), filenames)
after reading in list
, can rbind
datasets single 1 , have 'id' column indicate file came from. can useful in several operations.
dt <- rbindlist(lst, idcol="grp")
Comments
Post a Comment