比较两个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

查看:152
本文介绍了比较两个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天全站免登陆