在R中使用For循环导出多个csv文件?

时间:2018-04-03 06:54:29

标签: r loops dataframe read.csv

这是我使用的代码,但是我确实获得了所有csv文件,但是只有一行包含列名,没有其他数据......你能告诉我我的代码有什么问题吗?

m<-length(unique(rd_1$mall))
dataframe.list<-list()

for(i in 1:m){
dataframe.list[[i]] <- subset(rd_1, mall==i)
write.csv(dataframe.list[[i]], file = 
paste0("C:/Users/yogesh/Desktop/Work/Analysis/","mall_",i, 
".csv"), row.names = TRUE)
}

这是一个可重复的例子:

y <- length(unique(population$year))
dataframe.list <- list()


for (i in 1:y){
  dataframe.list[[i]] <- subset(population, year == i)
  write.csv(dataframe.list[[i]], file = paste0("year_", i), row.names = TRUE)
}
read.csv("year_1", row.names = 1)
# [1] country    year       population
# <0 rows> (or 0-length row.names)

1 个答案:

答案 0 :(得分:2)

当您在循环中运行第一行时:

dataframe.list[[i]] <- subset(rd_1, mall == i)

您正在rd_1中查找mall的值为1的行。鉴于你的第一线,我认为这不是你想要的。尝试创建一个新的向量,可以将其命名为malls。将其设置为unique(rd1$mall)。然后,在您进行分组时,请使用mall == malls[i],而不是mall == i

malls <-unique(rd_1$mall)
m <- length(malls)
dataframe.list<-list()

for(i in 1:m){
dataframe.list[[i]] <- subset(rd_1, mall==malls[i])
write.csv(dataframe.list[[i]], file = 
paste0("C:/Users/yogesh/Desktop/Work/Analysis/","mall_",i, 
".csv"), row.names = TRUE)
}

我们可以使用内置数据集population重现您的问题和解决方案。请注意,只是改进代码的附注。当您浏览1:m1:y时,您知道要经历多少个对象。分配列表的大小。这是dataframe.list <- vector("list", y)

问题:

y <- length(unique(population$year))
dataframe.list <- vector("list", y)


for (i in 1:y){
  dataframe.list[[i]] <- subset(population, year == i)
  write.csv(dataframe.list[[i]], file = paste0("year_", i), row.names = TRUE)
}
read.csv("year_1")
[1] X          country    year       population
<0 rows> (or 0-length row.names)

解决方案:

years <- unique(population$year)
y <- length(years)
dataframe.list <- vector("list", y)


for (i in 1:y){
  dataframe.list[[i]] <- subset(population, year == years[i])
  write.csv(dataframe.list[[i]], file = paste0("year_", i), row.names = TRUE)
}
head(read.csv("year.1", row.names = 1))
         country year population
1    Afghanistan 1995   17586073
2        Albania 1995    3357858
3        Algeria 1995   29315463
4 American Samoa 1995      52874
5        Andorra 1995      63854
6         Angola 1995   12104952