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?

1
  • Please make your question reproducible ... not knowing what na_s is makes this difficult to resolve. (Docs on minimal and reproducible questions.) Commented Feb 4, 2017 at 23:57

2 Answers 2

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)
}
Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
sounds, nice. you just need to fix the first answer, 1:N does not really work. :)
@m_c if N = length(na_sx) then it works, but I changed it anyways as it looks nicer.
if I use 1:N, it gives me an error, because it sees it as object, which is not existing.
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))  

2 Comments

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.
As it should. The differences are that the code in my answer doesn't need to reference list indices within the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.