列表l
有三个字符串,分别命名为一个,两个和三个。我想将l
转换为数据框,我需要一个名为n
的其他列。
l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")
我可以使用循环来完成它,但我确信有更有效的方法可以做到这一点。
out <- NULL
for (i in 1:length(n)){
step <- rep(n[i], length(l[[i]]))
out <- c(out, step)}
df <- as.data.frame(unlist(l))
df$n <- out
df
# unlist(l) n
#1 a one
#2 b one
#3 c two
#4 d two
#5 e two
#6 e three
答案 0 :(得分:5)
使用基数R,基本上可以用两行来完成。
l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")
#Create an appropriately sized vector of names
nameVector <- unlist(mapply(function(x,y){ rep(y, length(x)) }, l, n))
#Create the result
resultDF <- cbind.data.frame(unlist(l), nameVector)
> resultDF
unlist(l) nameVector
1 a one
2 b one
3 c two
4 d two
5 e two
6 e three
答案 1 :(得分:4)
另一个选择是在将列表的每个元素的名称设置为向量后使用stack
:
stack(setNames(l, n))
# values ind
#1 a one
#2 b one
#3 c two
#4 d two
#5 e two
#6 e three
答案 2 :(得分:3)
另一个类似的基本R选项:
do.call(rbind, Map(f = expand.grid, l = l, n = n, stringsAsFactors = F))
# l n
# 1 a one
# 2 b one
# 3 c two
# 4 d two
# 5 e two
# 6 e three
答案 3 :(得分:1)
另一个选项是来自melt
reshape2
library(reshape2)
melt(setNames(l, n))
# value L1
#1 a one
#2 b one
#3 c two
#4 d two
#5 e two
#6 e three
或base R
data.frame(value = unlist(l), key = rep(n, lengths(l)))
# value key
#1 a one
#2 b one
#3 c two
#4 d two
#5 e two
#6 e three