首页 > 解决方案 > 尝试逐行比较两个数据帧与 R 中的许多列并标记不正确的行

问题描述

我实际上试图做的是将一个具有有限数量的行和列的数据集(其中每一行都被验证为正确)与另一个将随时间变化的数据集进行比较,我需要确定其中的哪些行第二个数据集与第一个不匹配。这可以与我有答案键(数据框 1)和一个包含数百万行的数据框进行比较,我需要将其与答案键进行比较以确定哪些行匹配。

我已经阅读了很多解决方案,但还没有找到一个简洁的解决方案 - 有什么建议吗?

添加示例数据集以支持 - 数据集 1

library(tibble)

df1 <- tribble(
  ~bc, ~var1, ~var2, ~var3,
  "A", 324, 468, 462,
  "B", 223, 362, 328,
  "C", 187, 200, 229,
  "D", 286, 455, 423)

数据集 2

df2 <- tribble(
  ~bc, ~var1, ~var2, ~var3,
  "A", 324, 468, 462,
  "B", 223, 362, 328,
  "C", 187, 200, 229,
  "D", 286, 455, 423,
  "A", 324, 468, 462,
  "B", 223, 362, 421,
  "D", 286, 455, 423)

我要做的是通过与数据集 1 匹配的变量 bc 检查数据集 2。例如,数据集 2 中的第二个 D bc 不匹配不匹配数据集 1

标签: rcompare

解决方案


没有看到任何数据,很难回答你。

使用 which 函数可以告诉您哪些行符合某些条件。下面是一个如何使用 which 的示例。您可以将其更改为说 which(df2$answers %in% df1$answer_key) 或类似内容

# Load the data
data(iris)

# Take a look
head(iris)
which_example <- c(5.4, 4.6)

# The way I think of which is to ask R "which rows in iris$Sepal.Length are 5.4?"
which(iris$Sepal.Length %in% 5.4)
which(iris$Sepal.Length %in% which_example)

# Once you have the rows, you can display only those specific rows and all or some columns
# The format is df[row,column] 
# Which gives the rows. You can leave column blank to get all or enter specific ones
iris[which(iris$Sepal.Length %in% 5.4),]
iris[which(iris$Sepal.Length %in% 5.4),c(2,4)]

推荐阅读