How to prevent merge from reordering columns

后端 未结 4 1452
长情又很酷
长情又很酷 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: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.

提交回复
热议问题