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

故事扮演 提交于 2019-12-13 06:13:48

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37563164/how-to-use-lapply-to-put-elements-of-a-list-into-different-data-frames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!