根据另一列中的值删除重复项

标签 r dataframe filter

我有一个与此类似的数据集:

> dput(df1)
structure(list(Person_Id = c(123L, 123L, 123L, 123L, 123L, 
                             567L, 567L, 567L, 888L, 888L), 
               Result = c("Yes", "Yes", "Yes", "Yes", "Yes", 
                          "No", "No", "No", "No", "Yes")), 
          class = "data.frame", row.names = c(NA, -10L))

如您所见,Person_id 123567Result 值在整个数据帧中保持一致。但是,888Result 值有所不同。 我想过滤这个数据集:

  1. 如果给定 Person_id 的结果不同,我希望将其删除。
  2. 如果结果在整个数据帧中保持一致,则为给定的Person_id仅保留一行。

输出数据框应如下所示:

> dput(df2)
structure(list(Person_Id = c(123L, 567L), 
               Result = c("Yes", "No")), 
          class = "data.frame", row.names = c(NA, -2L))

最佳答案

使用聚合基本 R 方法

na.omit(aggregate(Result ~ Person_Id, df1, function(x) 
  ifelse(length(unique(x)) == 1, unique(x), NA)))
  Person_Id Result
1       123    Yes
2       567     No

关于根据另一列中的值删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75327830/

相关文章:

python-3.x - pandas 数据帧中的跳转点 : the moment when the value in a column gets changed

r - 在数据框中使用 ifelse 获取陈旧值

python - SQLAlchemy 按 PickleType 内容过滤查询

javascript - lodash _.filter 用于可选地基于数组的条件?

r - 意外的 R 内存管理行为

r - For 循环不使用 r 插入矩阵中的缺失值

r - R 3.2.3 中的 ggplot2 : layers broken?

r - ggplot2 中等效的定位器(用于 map )

python - 如何将数据从文本操作为 CSV

json - 在Powershell中过滤JSON