This question is not about how to make it work, if you are looking for that, here are some good answers. Thread1 , Thread2
My question is why this version does not work
#Creating a simple list
n <- 5
my_list <- lapply(1:n, function(i) data.frame(x = rnorm(10), y = rnorm(10)) )
names(my_list) <- letters[1:n]
#Trying to write as per my intuition, produces error
lapply(my_list,write.csv,paste0(names(my_list),".csv"))
Error in file(file, ifelse(append, "a", "w")) :
invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :
the condition has length > 1 and only the first element will be used
However, desired results can easily be achieved with
lapply(1:length(my_list), function(i) write.csv(my_list[[i]],
file = paste0(names(my_list[i]), ".csv")))
As I do not understand this error, I have so many doubts.
- Why do we need to write another function which works on individual list elements?
- Are there other similar functions, which can't be
used directly with
lapply
and need a similar treatment? And (even better), How do I recognize that whether a function needs such kind of treatment? - What are the potential benefits of such functions over the functions which
can directly be used with
lapply
?