How do I keep duplicates but remove unique values based on column in R

我们两清 提交于 2021-02-07 20:03:35

问题


How can I keep my duplicates, but remove unique values based on one column(qol)?

ID   qol  Sat
A     7   6
A     7   5
B     3   3 
B     3   4
B     1   7
C     2   7
c     1   2

But I need this:

ID   qol  Sat
A     7   6
A     7   5
B     3   3 
B     3   4

What can I do?


回答1:


dplyr solution:

library(dplyr)

ID <- c("A", "A", "B", "B", "B", "C", "c")
qol <- c(7,7,3,3,1,2,1)
Sat <- c(6,5,3,4,7,7,2)

test_df <- data.frame(cbind(ID, qol, Sat))

filtered_df <- test_df %>%
               group_by(qol) %>%
               filter(n()>1)

Please note that this will return

       ID    qol    Sat
1      A      7      6
2      A      7      5
3      B      3      3
4      B      3      4
5      B      1      7
6      c      1      2

If you also want to remove the two rows where qol == 1 but the IDs are different, just do:

filtered_df <- test_df %>%
               group_by(ID, qol) %>%
               filter(n()>1)

This will return the sample output you supplied in the question.



来源:https://stackoverflow.com/questions/52409999/how-do-i-keep-duplicates-but-remove-unique-values-based-on-column-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!