R 如何防止合并对列重新排序
在下面的示例中R 如何防止合并对列重新排序,r,sorting,merge,R,Sorting,Merge,在下面的示例中 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 <- x[c(2, 1, 3)] x您可以将其包装到自定义函数中。
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 <- x[c(2, 1, 3)]
x您可以将其包装到自定义函数中。例如:
merge.keep <- function(...,ord=union(names(x), names(y)))merge(...)[ord]
编辑我使用@Eddi idea设置ord的默认值。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
x以下是基本解决方案的通用版本:
merge(x, y)[, union(names(x), names(y))]
如果您只引入一列,并希望最后追加一列,那么merge
可能有些过分,您可以使用match
-[
索引方法进行辅助:
> 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
>x$isfruit x
代码食物是水果
17香蕉水果
2.8苹果果
爆米花不是水果
(合并函数中没有开关可用于执行您要求的操作。)我认为您的解决方案就是……尽管plyr包中的join
似乎没有对列进行重新排序。-1因为这不会向OP添加任何内容-OP想要的是不必指定顺序manually@eddi即使我不同意否决票,也能抓住好机会(我觉得有点尖锐)。我的想法是创建一个扩展合并函数的函数。我使用您的好主意编辑我的答案,以设置顺序的默认值。@agstudy您好,如果我有不同名称的数据表(例如x=DT1,y=DT2),并且如果我在这些数据表的不同列上合并,则此解决方案不起作用。Err msg:as.vector(x)中的错误:找不到对象“x”。这很有意义,因为数据表一开始并没有命名为x和y。我试图找到一个解决方法,但没有成功。您知道如何调整它通常适用的解决方案(更复杂)数据表合并?感谢您的输入,但我的真实数据涉及两个包含数十列的数据帧。plyr
一下子解决了我的一系列问题。感谢您的提示!请注意,为列名称传入union
只对数据帧有效,而不是对数据表。@Serenthia add,with=FALSE
为data.table代码>当使用“by.x=”和“by.y=”以及名称不同的列进行合并时,此操作失败。上述解决方法的一个丑陋版本是(使用OP修改的示例数据,将“food”和“food2”作为合并列):x
merge(x, y)[, union(names(x), names(y))]
> 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