Create a variable that identifies the original data.frame after rbind command in R

后端 未结 6 584
后悔当初
后悔当初 2020-12-11 06:07

I am relatively new to R and I would like to know how can I create a variable (number sequence) that identifies the each of the original data.frames before being joined with

6条回答
  •  执念已碎
    2020-12-11 06:26

    A fairly extensible solution:

    # test data:
    df1 <- data.frame(id=letters[1:2])
    df2 <- data.frame(id=letters[1:2])
    

    Collect your data into a list then rbind all at once:

    dfs <- c("df1","df2")
    do.call(rbind, Map("[<-", mget(dfs), TRUE, "source", dfs) )
    
    #      id source
    #df1.1  a    df1
    #df1.2  b    df1
    #df2.1  a    df2
    #df2.2  b    df2
    

    Also, note in this example that when you rbind using a named list, your rownames reference the source data. This means you can nearly get what you want using just:

    dfs <- c("df1","df2")
    do.call(rbind, mget(dfs) )
    
    #      id
    #df1.1  a
    #df1.2  b
    #df2.1  a
    #df2.2  b
    

提交回复
热议问题