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

后端 未结 6 1623
栀梦
栀梦 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 14:04

    I'm not sure if such a function already exists, but this seems to do the trick:

    bindAndSource <-  function(df1, df2) { 
      df1$source <- as.character(match.call())[[2]]
      df2$source <- as.character(match.call())[[3]]
      rbind(df1, df2)
    }
    

    results:

    bindAndSource(df1, df2)
    
    1 1 2    df1
    2 3 4    df1
    3 5 6    df2
    4 7 8    df2
    


    Caveat: This will not work in *aply-like calls

提交回复
热议问题