How to prevent merge from reordering columns

后端 未结 4 1422
长情又很酷
长情又很酷 2020-12-31 08:26

In the following example

x <- data.frame(code = 7:9, food = c(\'banana\', \'apple\', \'popcorn\'))
y <- data.frame(food = c(\'banana\', \'apple\', \'po         


        
相关标签:
4条回答
  • 2020-12-31 08:40

    Here's a generic version of your base workaround:

    merge(x, y)[, union(names(x), names(y))]
    
    0 讨论(0)
  • 2020-12-31 08:40

    If you only bring in one column and want to append it last then maybe merge is overkill and you can just do an assingment with a match-[indexing approach:

    > x$isfruit <- y$isfruit[match(y$food, x$food)]
    > x
      code    food   isfruit
    1    7  banana     fruit
    2    8   apple     fruit
    3    9 popcorn not fruit
    

    (There are no switches to throw in the merge function to do what you ask.)

    0 讨论(0)
  • 2020-12-31 08:51

    plyr makes this easy:

     x <- data.frame(code = 7:9, food = c('banana', 'apple', 'popcorn'))
     y <- data.frame(food = c('banana', 'apple', 'popcorn'),
                    isfruit = c('fruit', 'fruit', 'not fruit'))
    
    library(plyr)
    join(x,y)
    
            #GOOD 
    #Joining by: food
    #  code    food   isfruit
    #1    7  banana     fruit
    #2    8   apple     fruit
    #3    9 popcorn not fruit
    
        #BAD  
    # merge(x,y)
    #     food code   isfruit
    #1   apple    8     fruit
    #2  banana    7     fruit
    #3 popcorn    9 not fruit
    
    0 讨论(0)
  • 2020-12-31 08:59

    You can wrap it in your custom function. For example :

    merge.keep <- function(...,ord=union(names(x), names(y)))merge(...)[ord]
    

    then for example:

    merge.keep(x,y)
      code    food   isfruit
    1    8   apple     fruit
    2    7  banana     fruit
    3    9 popcorn not fruit
    

    EDIT I use @Eddi idea to set default values of ord.

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