Marco
Marco

Reputation: 39

How to use lapply to put elements of a list into different data frames

I have a list of dataframes called db; each data frame has its name. I use:

lapply(names(db),
       function(x)write.csv(db[x],
                            file =paste0(x,'.csv')))

to extract the d.frames and save them into csv files. Now i'm trying to extact from the list the dataframes and create different dataframes with this command:

lapply(names(db),
       function(x)as.data.frame(db[x]))

But it does not store any data frame into the workspace , how can I store each df with different names into the workspace?

Upvotes: 0

Views: 1229

Answers (1)

akrun
akrun

Reputation: 886938

We extract the list elements with [[

lapply(names(db), function(x) write.csv(db[[x]],
        file =paste0(x,'.csv'), row.names=FALSE, quote= FALSE))

as db[x] is still a list of data.frame with length 1.

If these are big datasets, the fwrite function from data.table would be more efficient

library(data.table)
lapply(names(db), function(x) fwrite(db[[x]], file = paste0(x, ".csv")))

Just to illustrate the issue,

set.seed(24)
db <- setNames(lapply(1:3, function(i) as.data.frame(matrix(sample(1:9, 
                             5*4, replace=TRUE), ncol=4))), paste0("df", 1:3))

The difference between the OP's approach and the [[ is in the OP's approach it will write the files with column names that have a prefix from the names of 'db' whereas the [[ will not have any such problem.


Regarding the second problem, that is creating multiple objects in the global environment, we can use list2env directly on the 'db'

list2env(db, envir = .GlobalEnv)

But, this is not recommended as it most of the operations can be done within the list itself.

df1
#  V1 V2 V3 V4
#1  3  9  6  9
#2  3  3  4  2
#3  7  7  7  1
#4  5  8  7  5
#5  6  3  3  2

Upvotes: 2

Related Questions