List l有三个字符串,分别命名为一个,两个和三个.我想转换l为数据帧,我需要一个名为的附加列n.
l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")
Run Code Online (Sandbox Code Playgroud)
我可以使用循环来完成它,但我确信有更有效的方法可以做到这一点.
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
Run Code Online (Sandbox Code Playgroud)
使用基数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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)