Simplest way to get rbind to ignore column names

后端 未结 2 1644
臣服心动
臣服心动 2020-11-27 18:38

This came up just in an answer to another question here. When you rbind two data frames, it matches columns by name rather than index, which can lead to unexpe

相关标签:
2条回答
  • 2020-11-27 19:14

    This seems pretty easy:

    mapply(c,df,df[,2:1])
         x y
    [1,] 1 3
    [2,] 2 4
    [3,] 3 1
    [4,] 4 2
    

    For this simple case, though, you have to turn it back into a dataframe (because mapply simplifies it to a matrix):

    as.data.frame(mapply(c,df,df[,2:1]))
      x y
    1 1 3
    2 2 4
    3 3 1
    4 4 2
    

    Important note 1: There appears to be a downside of type coercion when your dataframe contains vectors of different types:

    df<-data.frame(x=1:2,y=3:4,z=c('a','b'))
    mapply(c,df,df[,c(2:1,3)])
         x y z
    [1,] 1 3 2
    [2,] 2 4 1
    [3,] 3 1 2
    [4,] 4 2 1
    

    Important note 2: It also is terrible if you have factors.

    df<-data.frame(x=factor(1:2),y=factor(3:4))
    mapply(c,df[,1:2],df[,2:1])
         x y
    [1,] 1 1
    [2,] 2 2
    [3,] 1 1
    [4,] 2 2
    

    So, as long as you have all numeric data, it's okay.

    0 讨论(0)
  • 2020-11-27 19:29

    You might find setNames handy here...

    rbind(df, setNames(rev(df), names(df)))
    #  x y
    #1 1 3
    #2 2 4
    #3 3 1
    #4 4 2
    

    I suspect your real use-case is somewhat more complex. You can of course reorder columns in the first argument of setNames as you wish, just use names(df) in the second argument, so that the names of the reordered columns match the original.

    0 讨论(0)
提交回复
热议问题