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

时间:2019-02-21 18:54:50

标签: r

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

这是前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"

1 个答案:

答案 0 :(得分: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])