如何防止重新排序列的合并

Wal*_*cio 12 sorting merge r

在以下示例中

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'))
Run Code Online (Sandbox Code Playgroud)

我想这样做x <- merge(x, y),但问题是merge()重新排列列,以便by列(食物)首先出现.如何防止这种情况并且merge(x, y)使用x的相同列顺序并且只插入新变量(isFruit)作为第三列(即"code,food,isFruit"而不是"food,code,isFruit")?

我试过这个,但无济于事:

merge(x, y, sort = F)
Run Code Online (Sandbox Code Playgroud)

我的解决方法是在之后执行此操作

x <- x[c(2, 1, 3)]
Run Code Online (Sandbox Code Playgroud)

edd*_*ddi 24

以下是基础解决方法的通用版本:

merge(x, y)[, union(names(x), names(y))]
Run Code Online (Sandbox Code Playgroud)

  • @Serenthia 为“data.table”添加“, with = FALSE” (3认同)

use*_*1_G 11

plyr 让这很容易:

 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
Run Code Online (Sandbox Code Playgroud)


ags*_*udy 6

您可以将其包装在自定义函数中.例如 :

merge.keep <- function(...,ord=union(names(x), names(y)))merge(...)[ord]
Run Code Online (Sandbox Code Playgroud)

然后例如:

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

编辑我使用@Eddi的想法来设置ord的默认值.

  • -1因为这不会给OP增加任何东西 - OP想要的是**不是**必须手动指定订单 (2认同)