如何使用lapply将列表的元素放入不同的数据帧 [英] How to use lapply to put elements of a list into different data frames
问题描述
我有一个称为db的数据帧列表;每个数据框都有其名称. 我使用:
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')))
提取d.frame并将其保存到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]))
但是它没有将任何数据帧存储到工作空间中,如何将每个具有不同名称的df存储到工作空间中?
But it does not store any data frame into the workspace , how can I store each df with different names into the workspace?
推荐答案
我们用[[
lapply(names(db), function(x) write.csv(db[[x]],
file =paste0(x,'.csv'), row.names=FALSE, quote= FALSE))
因为db[x]
仍然是data.frame
与length
为1的list
.
如果这些是大型数据集,则data.table
中的fwrite
函数将更有效
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))
OP的方法与[[
的区别在于OP的方法将write
列名带有'db'的names
前缀的文件,而[[
则没有任何此类问题.
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.
关于第二个问题,即在全局环境中创建多个对象,我们可以直接在'db'上使用list2env
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)
但是,不建议这样做,因为大多数操作都可以在list
本身内完成.
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屋!