rbind dataframes with a different column name

前端 未结 5 517
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 20:28

I\'ve 12 data frames, each one contains 6 columns: 5 have the same name, 1 is different. Then when I call rbind() I get:

Error in match.names(cla         


        
5条回答
  •  北海茫月
    2020-11-27 20:45

    I would rename the columns. This is very easy with names() if the columns are in the same order.

    df1 <- data.frame(one=1:10,two=11:20,three=21:30)
    
    df2 <- data.frame(four=31:40,five=41:50,six=51:60)
    
    names(df2)<-names(df1)
    
    rbind(df1,df2)
    

    or

    df1 <- data.frame(one=1:10,two=11:20,three=21:30)
    
    df2 <- data.frame(four=31:40,five=41:50,six=51:60)
    
    rbind(df1,setnames(df2,names(df1)))
    

    Result:

       one two three
    1    1  11    21
    2    2  12    22
    3    3  13    23
    4    4  14    24
    5    5  15    25
    6    6  16    26
    7    7  17    27
    8    8  18    28
    9    9  19    29
    10  10  20    30
    11  31  41    51
    12  32  42    52
    13  33  43    53
    14  34  44    54
    15  35  45    55
    16  36  46    56
    17  37  47    57
    18  38  48    58
    19  39  49    59
    20  40  50    60
    

提交回复
热议问题