How to append group row into dataframe

后端 未结 9 2017
借酒劲吻你
借酒劲吻你 2021-02-07 10:55

I have this df1:

A B C
1 2 3
5 7 9

where A B C are columns names.

I have another df2 with one column:

A
1
         


        
9条回答
  •  悲&欢浪女
    2021-02-07 11:51

    For the sake of completeness, here is data.table approach which doesn't require to handle column names:

    library(data.table)
    setDT(df1)[, lapply(.SD, c, df2$A)]
    
       A B C
    1: 1 2 3
    2: 5 7 9
    3: 1 1 1
    4: 2 2 2
    5: 3 3 3
    6: 4 4 4
    

    Note that the OP has described df2 to consist only of one column.

    There is also a base R version of this approach:

    data.frame(lapply(df1, c, df2$A))
    
      A B C
    1 1 2 3
    2 5 7 9
    3 1 1 1
    4 2 2 2
    5 3 3 3
    6 4 4 4
    

    This is similar to d.b's approach but doesn't required to deal with column names.

提交回复
热议问题