比较两个 data.frames 以查找 data.frame 1 中不存在于 data.frame 2 中的行 [英] Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

查看:27
本文介绍了比较两个 data.frames 以查找 data.frame 1 中不存在于 data.frame 2 中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 2 个 data.frames:

I have the following 2 data.frames:

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])

我想找到 a1 行而 a2 没有的行.

I want to find the row a1 has that a2 doesn't.

是否有针对此类操作的内置函数?

Is there a built in function for this type of operation?

(ps:我确实为它写了一个解决方案,我只是好奇是否有人已经制作了更精心设计的代码)

(p.s: I did write a solution for it, I am simply curious if someone already made a more crafted code)

这是我的解决方案:

a1 <- data.frame(a = 1:5, b=letters[1:5])
a2 <- data.frame(a = 1:3, b=letters[1:3])

rows.in.a1.that.are.not.in.a2  <- function(a1,a2)
{
    a1.vec <- apply(a1, 1, paste, collapse = "")
    a2.vec <- apply(a2, 1, paste, collapse = "")
    a1.without.a2.rows <- a1[!a1.vec %in% a2.vec,]
    return(a1.without.a2.rows)
}
rows.in.a1.that.are.not.in.a2(a1,a2)

推荐答案

这不会直接回答您的问题,但会为您提供共同的元素.这可以通过 Paul Murrell 的包 compare:

This doesn't answer your question directly, but it will give you the elements that are in common. This can be done with Paul Murrell's package compare:

library(compare)
a1 <- data.frame(a = 1:5, b = letters[1:5])
a2 <- data.frame(a = 1:3, b = letters[1:3])
comparison <- compare(a1,a2,allowAll=TRUE)
comparison$tM
#  a b
#1 1 a
#2 2 b
#3 3 c

函数 compare 在允许的比较类型方面为您提供了很大的灵活性(例如,更改每个向量的元素顺序、更改变量的顺序和名称、缩短变量、更改大小写)字符串).从中,您应该能够找出其中一个遗漏了什么.例如(这不是很优雅):

The function compare gives you a lot of flexibility in terms of what kind of comparisons are allowed (e.g. changing order of elements of each vector, changing order and names of variables, shortening variables, changing case of strings). From this, you should be able to figure out what was missing from one or the other. For example (this is not very elegant):

difference <-
   data.frame(lapply(1:ncol(a1),function(i)setdiff(a1[,i],comparison$tM[,i])))
colnames(difference) <- colnames(a1)
difference
#  a b
#1 4 d
#2 5 e

这篇关于比较两个 data.frames 以查找 data.frame 1 中不存在于 data.frame 2 中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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