将列表转换为R中的数据框,并添加带有子列表名称的列 [英] Convert list to dataframe in R and add column with names of sub-lists
本文介绍了将列表转换为R中的数据框,并添加带有子列表名称的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
列表l
具有三个分别命名为一,二和三的字符串.我想将l
转换为数据框,并且我需要在n
中具有名称的附加列.
List l
has three strings that are named one, two, and three, respectively. I want to convert l
to a dataframe, and I need an additional column with the names in n
.
l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")
我可以使用循环来做到这一点,但是我敢肯定,有更有效的方法可以做到这一点.
I can do it using a loop, but I'm sure there are more efficient ways of doing this.
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
推荐答案
另一种选择是在将列表中每个元素的名称设置为向量之后使用stack
:
Another option is to use stack
after setting the name for each element of the list to be the vector:
stack(setNames(l, n))
# values ind
#1 a one
#2 b one
#3 c two
#4 d two
#5 e two
#6 e three
这篇关于将列表转换为R中的数据框,并添加带有子列表名称的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文