Combine (rbind) data frames and create column with name of original data frames

后端 未结 6 1630
栀梦
栀梦 2020-11-22 13:12

I have several data frames that I want to combine by row. In the resulting single data frame, I want to create a new variable identifying which data set the observation came

6条回答
  •  没有蜡笔的小新
    2020-11-22 13:47

    A blend of the other two answers:

    df1 <- data.frame(x = 1:3,y = 1:3)
    df2 <- data.frame(x = 4:6,y = 4:6)
    
    > foo <- function(...){
        args <- list(...)
        result <- do.call(rbind,args)
        result$source <- rep(as.character(match.call()[-1]),times = sapply(args,nrow))
        result
     }
    
    > foo(df1,df2,df1)
      x y source
    1 1 1    df1
    2 2 2    df1
    3 3 3    df1
    4 4 4    df2
    5 5 5    df2
    6 6 6    df2
    7 1 1    df1
    8 2 2    df1
    9 3 3    df1
    

    If you want to avoid the match.call business, you can always limit yourself to naming the function arguments (i.e. df1 = df1, df2 = df2) and using names(args) to access the names.

提交回复
热议问题