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

问题描述 投票:1回答:1

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

以下是前两个更高级别的列表。目标是输出具有两列的数据帧。第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"
r
1个回答
2
投票

编写一个执行您想要的功能,并使用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])
© www.soinside.com 2019 - 2024. All rights reserved.