发现数据帧之间的不匹配

问题描述 投票:0回答:1

我有一个称为ref的参考数据帧。我想将ref中的元素与一组数据帧进行比较,然后将不匹配项插入列表中。值为0、1和NA。下面的样本数据集:

ref <- structure(list(ID = structure(c(2L, 1L, 3L), .Label = c("bar", 
"foo", "hello"), class = "factor"), a = c(1, 0, 0), b = c(1, 
1, 0), c = c(1, 1, 1)), class = "data.frame", row.names = c(NA, 
-3L))

df1 <- structure(list(ID = structure(2:1, .Label = c("bar", "foo"), class = "factor"), 
    b = c(0, 0), f = c(NA, 0), a = c(1, 1)), class = "data.frame", row.names = c(NA, 
-2L))

ref:

     ID a b c
1   foo 1 1 1
2   bar 0 1 1
3 hello 0 0 1

df1

   ID b f  a
1 foo 0 NA 1
2 bar 0 0  1

数据帧未排序。引用ID均包含在内。目的是比较具有相同ID和colname的元素,并根据colname列出不匹配项。 df1的所需列表为:

df1_list

$a
[1] "bar"

$b
[1] "foo" "bar"

主要问题是列名不是全部相同,也不是按顺序排列。如果我要对许多数据帧中的每一个执行此操作,则将变得相当复杂。我也无法通过连接函数解决此问题。

r dataframe
1个回答
0
投票

这里是使用底数R的一种方法:

cols <- intersect(names(df1[-1]), names(ref[-1]))
rows <- match(df1$ID, ref$ID)
apply(df1[cols] != ref[rows, cols], 2, function(x) as.character(df1$ID[x]))

#$b
#[1] "foo" "bar"

#$a
#[1] "bar"
© www.soinside.com 2019 - 2024. All rights reserved.