将嵌套列表的第一个元素绑定到嵌套列表的后续元素

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (42)

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

以下是前两个更高级别的列表。目标是输出具有两列的数据帧。第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"
提问于
用户回答回答于

编写一个能够执行所需操作的函数,并将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])

所属标签

可能回答问题的人

  • 天使的炫翼

    15 粉丝531 提问35 回答
  • 旺仔小小鹿

    社区 · 运营 (已认证)

    48 粉丝0 提问27 回答
  • 富有想象力的人

    2 粉丝0 提问26 回答
  • 发条丶魔灵1

    6 粉丝525 提问25 回答

扫码关注云+社区

领取腾讯云代金券