0

我有一个名称数组和一个返回数据框的函数。我想结合这个数组和数据框。例如:

>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)

我想要的是一个将这个数组与数据框连接起来的数据框。df1 对应“a”,df2 对应“b”,依此类推。因此,最终的数据框如下所示:

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

有人可以帮我吗?

谢谢。

4

1 回答 1

2

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.frames, 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.

于 2013-04-30T05:25:54.280 回答