【问题标题】:Bind first element of nested list to the subsequent elements of nested list将嵌套列表的第一个元素绑定到嵌套列表的后续元素
【发布时间】:2019-02-21 18:54:49
【问题描述】:

我有一个嵌套列表,我想将每个列表的第一个元素绑定到该嵌套列表的其余元素。 (对整个集合中的每个列表执行此操作)

这是前 2 个更高级别的列表。目标是输出一个包含两列的数据框。第 1 列是第一行,第 2 列是后续行。

简化版:

list(c("Location1", 
       "Location1_Bid1", 
       "Location1_Bid2", 
       "Location1_Bid3"), 
     c("Location2", 
     "Location2_Bid1", 
     "Location2_Bid2", 
     "Location2_Bid3"),
     c("Location3", 
     "Location3_Bid1", 
     "Location3_Bid2", 
     "Location3_Bid3",
     "Location3_Bid4")
     , c("Location4", 
     "Location4_Bid1", 
     "Location4_Bid2"))

例如:

Location        |  Bid
"Location1"     | "Location1_Bid1"
"Location1"     | "Location1_Bid2"
"Location1"     | "Location1_Bid3"
"Location2"     | "Location2_Bid1"
"Location2"     | "Location2_Bid2"
"Location2"     | "Location2_Bid3"
"Location3"     | "Location3_Bid1"
"Location3"     | "Location3_Bid2"
"Location3"     | "Location3_Bid3"
"Location3"     | "Location3_Bid4"
"Location4"     | "Location4_Bid1"
"Location4"     | "Location4_Bid2"

【问题讨论】:

  • 您能否与dput() 分享您的示例输入,以便可以复制粘贴?将您在问题中提出的内容读入 R 真的很痛苦。
  • 或者,只需创建数据的简化示例。例如,lst <- list(a = list(...), b = list(...)) - 很可能使用简化的列表结构来创建问题的要点。
  • 我不想要链接和下载,只想要一些可复制粘贴的 R 语法。 dput(your_list[1:2]) 之类的东西,或者太长的 dput(lapply(your_list[1:2], "[", 1:4))
  • 现在正在开发简化版@JasonAizkalns
  • @Gregor 这样更好吗?

标签: r


【解决方案1】:

编写一个函数来执行您想要的操作,并使用lapply 对每个列表项执行此操作:

foo = function(x) cbind(x[1], x[-1])
result = lapply(your_list, foo)

将您的简单示例称为“简单”:

lapply(simple, foo)
# [[1]]
#      [,1]        [,2]            
# [1,] "Location1" "Location1_Bid1"
# [2,] "Location1" "Location1_Bid2"
# [3,] "Location1" "Location1_Bid3"
# 
# [[2]]
#      [,1]        [,2]            
# [1,] "Location2" "Location2_Bid1"
# [2,] "Location2" "Location2_Bid2"
# [3,] "Location2" "Location2_Bid3"
# 
# [[3]]
#      [,1]        [,2]            
# [1,] "Location3" "Location3_Bid1"
# [2,] "Location3" "Location3_Bid2"
# [3,] "Location3" "Location3_Bid3"
# [4,] "Location3" "Location3_Bid4"
# 
# [[4]]
#      [,1]        [,2]            
# [1,] "Location4" "Location4_Bid1"
# [2,] "Location4" "Location4_Bid2"

这些是矩阵,而不是数据框。如果你想要数据帧,你可以使用cbind.data.frame 而不是cbind。您还可以在示例输出中添加列名,例如

foo = function(x) cbind.data.frame(Location = x[1], Bid = x[-1])

【讨论】:

  • 我能够使 Matrix 解决方案正常工作,但是当我使用 cbind.data.frame() 时出现错误:data.frame 中的错误(...,check.names = FALSE) : 参数暗示不同的行数:1, 0
  • 这很奇怪,cbind.data.frame 版本适用于您的简单示例和您使用 dput 的数据以及此后删除的数据。如果你能找到一个失败的最小示例,我可以帮助调试,但现在我只看到它工作。
  • 我在“简单示例”上运行它时遇到同样的错误,idk
  • 也许有些包在掩饰东西?我刚刚重新启动 R,只运行了 foo 定义、simple 定义和 lapply(simple, foo),它工作正常。
  • 我已经重新启动了 R。取出除 pdftools 和 stringr 之外的所有包。你知道做同样事情的任何替代功能吗?当我运行调试器时,它似乎指向我的 data.frame() 函数中的问题。
猜你喜欢
  • 1970-01-01
  • 2013-12-24
  • 2014-11-06
  • 2021-04-21
  • 2023-03-22
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多