Export multiple .csv files to R

3

I'm trying to export multiple files .csv to R through the lapply function. These files are within a list. I've tried the following settings:

lapply(list,function(x)
write.csv2(list$x,paste0(x),row.names=FALSE))

lapply(seq_along(list),function(x)
write.csv2(list$x,paste0(x),row.names=FALSE))

among others, which returned error messages.

The dput (a list, in fact) follows below:

lista=structure(list(dados1 = structure(list(aa = c(1, 2, 3, 4, 5, 
6, 7), bb = c(1, 2, 3, 4, 5, 6, 7)), .Names = c("aa", "bb"), row.names = c(NA, 
-7L), class = "data.frame"), dados2 = structure(list(cc = c(1, 
2, 3, 4, 5, 6, 7), dd = c(1, 2, 3, 4, 5, 6, 7)), .Names = c("cc", 
"dd"), row.names = c(NA, -7L), class = "data.frame")), .Names = c("dados1", 
"dados2"))

I need a response with lapply , because with for I can do the export. This way, it's more of a curiosity to know why lapply does not work.

    
asked by anonymous 27.10.2018 / 22:04

1 answer

3

I think the problem is with the indexing you use: $ . We can access each element of a list with $ and [[]] :

lista$dados1
# aa bb
# 1  1  1
# 2  2  2
# 3  3  3
# 4  4  4
# 5  5  5
# 6  6  6
# 7  7  7

lista[[1]]
# aa bb
# 1  1  1
# 2  2  2
# 3  3  3
# 4  4  4
# 5  5  5
# 6  6  6
# 7  7  7

But for a reason unknown to me, when we use laapply() only [[]] works. Maybe this part of help(lapply) might explain:

  

For historical reasons, the calls created by 'lapply' are   unevaluated, and code has been written (e.g., 'bquote') that   relies on this. This means that the call is always of   the form 'FUN (X [[i]], ...)', with 'i' replaced by the current   (integer or double) index. This is not normally a problem, but it   can be if 'FUN' use 'sys.call' or 'match.call' or if it is a   primitive function that makes use of the call. This means that it   is often safer to call primitive functions with a wrapper, so that   e.g., lapply (ll, function (x) is.numeric (x)) is required to ensure   that method dispatch for 'is.numeric' occurs correctly.

So, your example will work if you use [[]] instead of $ :

lapply(seq_along(lista),function(x) write.csv2(lista[[x]],
                                   file = paste0(names(lista[x]), '.csv'),
                                   row.names = FALSE))
    
29.10.2018 / 16:58