在R中的数据框中组合两个列表

Ram*_*ham 12 merge r list dataframe

我有两个不同结构的列表:

listA <- list(c("a","b","c"), c("d","e"))
listB <- list(0.05, 0.5)

listA
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "d" "e"

listB
[[1]]
[1] 0.05

[[2]]
[1] 0.5
Run Code Online (Sandbox Code Playgroud)

我知道如何使用循环将两个列表组合在一个看起来像下面的数据框中,但我确信有一种更有效的方法.

data.frame(A = c("a","b","c","d","e"), B = c(rep(0.05,3), rep(0.5,2)))
  A    B
1 a 0.05
2 b 0.05
3 c 0.05
4 d 0.50
5 e 0.50
Run Code Online (Sandbox Code Playgroud)

Mat*_*rde 19

这是另一种选择:

do.call(rbind, Map(data.frame, A=listA, B=listB))

#   A    B
# 1 a 0.05
# 2 b 0.05
# 3 c 0.05
# 4 d 0.50
# 5 e 0.50
Run Code Online (Sandbox Code Playgroud)


Ren*_*rop 5

也许有一种更优雅的方式来保留's 元素numeric的类list2......但这也有效

df <- do.call(rbind,mapply(cbind, listA, listB))
df <- as.data.frame(df, stringsAsFactors = FALSE)
df[,2] <- as.numeric(df[,2])
Run Code Online (Sandbox Code Playgroud)

编辑MapMatthew Plourde 使用aka的解决方案更好mapply(data.frame, A=listA, B=listB, SIMPLIFY = FALSE)