简体   繁体   English

R:将列表与数据帧组合

[英]R: Combine a list to a data frame

I have a array of names and a function that returns a data frame. 我有一个名称数组和一个返回数据框的函数。 I want to combine this array and data frame. 我想结合这个数组和数据框架。 For eg: 例如:

>mynames<-c("a", "b", "c")
>df1 <- data.frame(val0=c("d", "e"),val1=4:5)
>df2 <- data.frame(val1=c("e", "f"),val2=5:6)
>df3 <- data.frame(val2=c("f", "g"),val3=6:7)

What I want is a data frame that joins this array with data frame. 我想要的是一个数据框,将数组与数据框连接起来。 df1 corresponds to "a", df2 corresponds to "b" and so on. df1对应于“a”,df2对应于“b”,依此类推。 So, the final data frame looks like this: 所以,最终的数据框如下所示:

Names Var    Val
a     d      4
a     e      5
b     e      5
b     f      6
c     f      6
c     g      7

Can someone help me on this? 有人可以帮我吗?

Thanks. 谢谢。

This answers this particular question, but I'm not sure how much help it will be for your actual problem: 这回答了这个特殊的问题,但我不确定它对你的实际问题有多大的帮助:

myList <- list(df1, df2, df3)
do.call(rbind, 
        lapply(seq_along(mynames), function(x) 
          cbind(Names = mynames[x], setNames(myList[[x]], 
                                             c("Var", "Val")))))
#   Names Var Val
# 1     a   d   4
# 2     a   e   5
# 3     b   e   5
# 4     b   f   6
# 5     c   f   6
# 6     c   g   7

Here, we create a list of your data.frame s, and in our lapply call, we add in the new "Names" column and rename the existing columns so that we can use rbind to put them all together. 在这里,我们创建一个data.frame的列表,在我们的lapply调用中,我们添加新的“Names”列并重命名现有的列,以便我们可以使用rbind将它们放在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM