2

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?

m_c
  • 496
  • 2
  • 19
  • Please make your question reproducible ... not knowing what `na_s` is makes this difficult to resolve. (Docs on [minimal](http://stackoverflow.com/help/mcve) and [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) questions.) – r2evans Feb 04 '17 at 23:57

2 Answers2

2

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)
}
tatxif
  • 438
  • 6
  • 10
  • I dont think that this solves my problem, and apply needs and argument to be passed on which object some function will be applied. which is a list `na_s` – m_c Feb 05 '17 at 09:12
  • @m_c glad it worked! I updated the for loop too, if you just need to save each element. Please accept my answer if it helped you. – tatxif Feb 05 '17 at 18:37
  • sounds, nice. you just need to fix the first answer, 1:N does not really work. :) – m_c Feb 05 '17 at 18:45
  • @m_c if N = length(na_sx) then it works, but I changed it anyways as it looks nicer. – tatxif Feb 05 '17 at 21:25
  • if I use 1:N, it gives me an error, because it sees it as object, which is not existing. – m_c Feb 06 '17 at 08:07
2

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))  
Jake Kaupp
  • 7,892
  • 2
  • 26
  • 36
  • `lapply(1:length(na_s), function (x) write.csv(na_s[[x]],file = paste('./na_s_monthly/','na_',names (na_s[x]),'.csv',sep=""), row.names = F))` worked for me. – m_c Feb 05 '17 at 18:18
  • As it should. The differences are that the code in my answer doesn't need to reference list indices within the function. – Jake Kaupp Feb 05 '17 at 18:22