如何使用 lapply 将列表的元素放入不同的数据框中 [英] How to use lapply to put elements of a list into different data frames

查看:28
本文介绍了如何使用 lapply 将列表的元素放入不同的数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 db 的数据框列表;每个数据框都有它的名字.我用:

lapply(names(db),函数(x)write.csv(db[x],文件 =paste0(x,'.csv')))

提取 d.frames 并将它们保存到 csv 文件中.现在我正在尝试从列表中提取数据帧并使用以下命令创建不同的数据帧:

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

但是它没有将任何数据框存储到工作区中,如何将每个具有不同名称的 df 存储到工作区中?

解决方案

我们用[[

提取list元素

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

as db[x] 仍然是 data.framelist length 1 >

如果这些是大数据集,data.table 中的 fwrite 函数会更有效

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

<小时>

只是为了说明问题,

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))

OP 的方法和 [[ 之间的区别在于 OP 的方法它将 write 列名的文件具有来自 names 的前缀 of 'db' 而 [[ 不会有任何这样的问题.

<小时>

关于第二个问题,即在全局环境中创建多个对象,我们可以直接在'db'上使用list2env

list2env(db,envir = .GlobalEnv)

但是,不建议这样做,因为它的大部分操作都可以在 list 本身内完成.

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

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?

解决方案

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

这篇关于如何使用 lapply 将列表的元素放入不同的数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆