Search code examples
rdataframedata-management

R Code for removing values within a group


I am working with data similar to the data below:

ID <- seq(1,10,1)
Letter <- c("A", "B", "C","C", "C", "D", "D", "E","F", "F")
df<- data.frame(ID, Letter)
   ID Letter
1   1      A
2   2      B
3   3      C
4   4      C
5   5      C
6   6      D
7   7      D
8   8      E
9   9      F
10 10      F

Looking specifically at the Letter column, I want to subset the data such that the Letter column only includes the ID value 4. But I want to keep all other values as well. So the data looks like:

   ID Letter
1   1      A
2   2      B
4   4      C
6   6      D
7   7      D
8   8      E
9   9      F
10 10      F

Any help you can offer would be greatly appreciated!


Solution

  • Here is a base R option

    subset(df,ave(ID==4,Letter,FUN = function(x) Negate(any)(x)|x))
    

    giving

       ID Letter
    1   1      A
    2   2      B
    4   4      C
    6   6      D
    7   7      D
    8   8      E
    9   9      F
    10 10      F