[英]Combine two lists in a dataframe in R
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
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
Maybe there is a more elegant way that keeps the class numeric
of list2
's elements... But this one works as well也许有一种更优雅的方法可以保留list2
元素的类numeric
......但这也有效
df <- do.call(rbind,mapply(cbind, listA, listB))
df <- as.data.frame(df, stringsAsFactors = FALSE)
df[,2] <- as.numeric(df[,2])
EDIT Way 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)
另一种不使用 do.call 的方法:
cbind(data.frame(listA), data.frame(listB))
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
If looking for a tidyverse
solution, here is the analogue to the accepted answer.如果正在寻找tidyverse
解决方案,这里是已接受答案的类比。 Using the dfr
suffix to the map
function family enables a very simple solution which should also be faster than do.call("rbind")
.使用map
函数系列的dfr
后缀可以实现一个非常简单的解决方案,它也应该比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 日创建
Here is another way:这是另一种方式:
do.call(rbind,
lapply(1:length(listA),
function(i)
data.frame(A=unlist(listA[i]),
B=unlist(listB[i]))))
This places the index and renames the columns appropriately:这将放置索引并适当地重命名列:
df <- do.call(rbind.data.frame, Map('c', listA, listB))
colnames(df)[1] <- "A"
colnames(df)[2] <- "B"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.