Export multiple. csv files in R

Asked

Viewed 128 times

2

I’m trying to export multiple files .csv in R through the function lapply. These files are within a list. I 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, actually) 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 an answer with lapply, because with for I can do the export. This way, it is more a curiosity to know why of lapply not work.

1 answer

2


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

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

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

For Historical reasons, the calls created by ːlapply' are unevaluated, and code has been Written (e.g., pra bquote') that relies on this. This Means that the Recorded 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' uses ?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))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.