list 在 R 中的数据框中组合两个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28630024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combine two lists in a dataframe in R
提问by Rami Al-Fahham
I have two lists with different structure:
我有两个结构不同的列表:
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
I have an idea of how to use looping to combine both lists in a dataframe that looks like the one below but I'm sure that there is a more efficient way of doing this.
我有一个关于如何使用循环将两个列表组合到一个如下所示的数据框中的想法,但我确信有一种更有效的方法来做到这一点。
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
回答by Matthew Plourde
This is another option:
这是另一种选择:
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
回答by Rentrop
Maybe there is a more elegant way that keeps the class numeric
of list2
's elements... But this one works as well
也许有,保持类更优雅的方式numeric
中list2
的元素......但是,这一件作品,以及
df <- do.call(rbind,mapply(cbind, listA, listB))
df <- as.data.frame(df, stringsAsFactors = FALSE)
df[,2] <- as.numeric(df[,2])
EDITWay better is Matthew Plourde's solution using Map
aka mapply(data.frame, A=listA, B=listB, SIMPLIFY = FALSE)
编辑方式更好的是 Matthew Plourde 使用Map
aka的解决方案mapply(data.frame, A=listA, B=listB, SIMPLIFY = FALSE)
回答by Calum You
If looking for a tidyverse
solution, here is the analogue to the accepted answer. Using the dfr
suffix to the map
function family enables a very simple solution which should also be faster than do.call("rbind")
.
如果正在寻找tidyverse
解决方案,这里是已接受答案的类比。使用函数系列的dfr
后缀可以map
实现一个非常简单的解决方案,该解决方案也应该比do.call("rbind")
.
library(tidyverse)
listA <- list(c("a","b","c"), c("d","e"))
listB <- list(0.05, 0.5)
map2_dfr(listA, listB, ~ tibble(A = .x, B = .y))
#> # A tibble: 5 x 2
#> A B
#> <chr> <dbl>
#> 1 a 0.05
#> 2 b 0.05
#> 3 c 0.05
#> 4 d 0.5
#> 5 e 0.5
Created on 2019-02-12 by the reprex package(v0.2.1)
由reprex 包(v0.2.1)于 2019 年 2 月 12 日创建
回答by Roland
I'd prefer this:
我更喜欢这个:
do.call(rbind,
Map(function(...) setNames(cbind.data.frame(...),
c("A", "B")),
listA, listB))
# A B
#1 a 0.05
#2 b 0.05
#3 c 0.05
#4 d 0.50
#5 e 0.50
回答by S.Zhong
Another way without using do.call:
另一种不使用 do.call 的方法:
cbind(data.frame(listA), data.frame(listB))
回答by zx8754
Here is another way:
这是另一种方式:
do.call(rbind,
lapply(1:length(listA),
function(i)
data.frame(A=unlist(listA[i]),
B=unlist(listB[i]))))