Yogesh Kumar
Yogesh Kumar

Reputation: 659

Exporting multiple csv files using For loop in R?

This is the code I have used ,but I do get all csv files ,but with just one single row with column names , no other data ...Can you pls tell me what is wrong with my code ?

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)
}

Here is a reproducible example:

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)

Upvotes: 1

Views: 2929

Answers (1)

De Novo
De Novo

Reputation: 7610

When you run your first line in the loop:

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

You are looking for those rows in rd_1 where the value for mall is 1. Given your first line, I don't think that is what you want. Try creating a new vector, maybe name it malls. Set that to unique(rd1$mall). Then as you subset, use mall == malls[i], instead of 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)
}

We can reproduce your problem and the solution with population, the built in data set. Notice, just a side note to improve your code. When you loop through 1:m, or here, 1:y, you know how many objects you're going to go through. Allocate the size of the list. Here it's dataframe.list <- vector("list", y)

Problem:

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)

Solution:

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

Upvotes: 2

Related Questions