我试图重复相同的命令x次,一个简单的例子是读取具有相同名称但不同年份的文件10次,我可以这样做
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 )
这很糟糕,因为我重复自己,如果有太多文件或者我必须重复太多次,它真的很耗时。我试过去探索
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 )
}
由于左侧而无法正常工作,而且
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 )
}
我要求在此过程中进一步向下,我必须每年处理我的数据,这意味着每年分配更多重复的命令。