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

后端 未结 6 1666
栀梦
栀梦 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:55

    Another approach using dplyr:

    df1 <- data.frame(x = c(1,3), y = c(2,4))
    df2 <- data.frame(x = c(5,7), y = c(6,8))
    
    df3 <- dplyr::bind_rows(list(df1=df1, df2=df2), .id = 'source')
    
    df3
    Source: local data frame [4 x 3]
    
      source     x     y
       (chr) (dbl) (dbl)
    1    df1     1     2
    2    df1     3     4
    3    df2     5     6
    4    df2     7     8
    

提交回复
热议问题