m_c
m_c

Reputation: 516

write.csv on a list of data frames

I ma trying to save a number of data frames from a list in separate directory. something is wrong with my code:

lapply(na_s, function (x) write.csv(na_s[[x]],file = paste('/na_s_daily/',names (na_s[x]),'.csv',sep=""), row.names = F)) 

Error code:

Error in na_s[[x]] : invalid subscript type 'list'

Anybody can see what I am doing wrong?

Upvotes: 2

Views: 2162

Answers (2)

tatxif
tatxif

Reputation: 438

The problem is that the input x is a number not the element of a list. Try

 lapply(1:length(na_sx),  function (x) write.csv(na_s[[x]],file = paste('./na_s_daily/','na_', names (na_s[x]),'.csv',sep=""), row.names = F)) 

Note that the above will also return a list of the data frames. So if you just need to save each element of the list as a data frame in your directory just do

for(x in 1:length(na_s)){
   write.csv(na_s[[x]],file = paste('./na_s_daily/','na_',names (na_s[x]),'.csv',sep=""), row.names = F)
}

Upvotes: 2

Jake Kaupp
Jake Kaupp

Reputation: 8072

If you want to use the names of the list, I would suggest using mapply. You also need to be sure the output directory exists before you use it, else you'll receive an error. I also changed paste to paste0 (which is paste(x, sep = "")).

na_s <- list("one" = mtcars, "two" = mtcars, "three" = mtcars)

mapply(function (x,y) write.csv(x, file = paste0('./na_s_daily/', y, '.csv'), row.names = F), na_s, names(na_s))  

Upvotes: 2

Related Questions