【问题标题】:How to modify a list of data.frame and then output the data.frame如何修改data.frame列表然后输出data.frame
【发布时间】:2021-06-01 09:42:38
【问题描述】:

我想在每个 data.frames 列表中创建第二列,它只是第一列的副本,然后输出这些 data.frames:

存储数据帧:

> FileList <- list(DF1, DF2)

为每个数据框添加另一列:

> ModifiedDataFrames <- lapply(1:length(FileList), function (x) {FileList[[x]]$Column2 == FileList[[x]]$Column1})

ModifiedDataFrames[[1]] 只返回一个列表,其中包含我认为来自 DF1$Column1 的内容

我在这里错过了什么?

【问题讨论】:

  • 您的函数应该返回更新后的 data.frame。当您进行分配时,只返回右手术语,而不是 data.frame。您可以将return(FileList[[x]]) 添加到您的函数中。如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • @MrFlick 好的,因为您需要指定 sapply 应该返回的内容,否则它只会从函数运行中返回标准。所以在这种情况下它只是返回FileList[[x]]$Column1

标签: r dataframe loops apply sapply


【解决方案1】:

您的代码存在一些问题。首先,您使用等价运算符== 进行赋值,其次您没有从函数中返回正确的元素。这是一个可能的解决方案:

df1 <- data.frame(Column1 = c(1:3))  
df2 <- data.frame(Column1 = c(4:6))  
FileList <- list(df1, df2)
ModifiedDataFrames <- lapply(FileList, function(x) {
  x$Column2 <- x$Column1
  return(x)
})

> ModifiedDataFrames
[[1]]
  Column1 Column2
1       1       1
2       2       2
3       3       3

[[2]]
  Column1 Column2
1       4       4
2       5       5

【讨论】:

  • 是的,等价​​运算符不起作用,我只是感到沮丧并尝试随机的事情。指定返回元素是我所缺少的。谢谢抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多