如何防止合并对列重新排序 [英] How to prevent merge from reordering columns

查看:70
本文介绍了如何防止合并对列重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中

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'))

我想做x <- merge(x, y),但是问题是merge()重新排序列,以便by列(食物)排在最前面. 如何防止这种情况,并让merge(x, y)使用x的相同列顺序,然后将新变量(isFruit)插入第三列(即代码,食物,isFruit"而不是食物,代码, isFruit")?

I would like to do x <- merge(x, y), but the problem is that merge() reorders the columns so that the by column (food) comes first. How can I prevent this and have merge(x, y) use the same column order of x and just insert the new variable (isFruit) as the third column (i.e., "code, food, isFruit" instead of "food, code, isFruit")?

我已经尝试过了,但无济于事:

I've tried this, to no avail:

merge(x, y, sort = F)

我的解决方法是事后进行

My workaround is to do this afterward

x <- x[c(2, 1, 3)]

推荐答案

这是您的基本解决方法的通用版本:

Here's a generic version of your base workaround:

merge(x, y)[, union(names(x), names(y))]

这篇关于如何防止合并对列重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆