Home > database >  Use the categorical values of columns to delete the idex in R
Use the categorical values of columns to delete the idex in R

Time:10-19

I made a simple data as follow:

data<-data.frame(id=c(1,1,1,2,2,2,3,3,4,4),
                 a=c(0,0,1,0,0,0,1,1,1,1),
                 b=c(1,0,0,0,0,0,0,1,1,0))

id stands for specific id number of a person. What I want to do now is delete the whole id if aequals 1. Aso, I want to delete the whole id if b equals 1. In this example, the desired output should be like this:

data<-data.frame(id=c(2,2,2),
                 a=c(0,0,0),
                 b=c(0,0,0))

In my actual data, there are hundreds of id,so I want to know method to do this.

CodePudding user response:

With Base R,

data[!(data$id %in% unique(data[(data$a == 1) |  (data$b == 1),"id"])),]

gives,

#       id a b
#     4  2 0 0
#     5  2 0 0
#     6  2 0 0

CodePudding user response:

In dplyr, with if_all:

data %>% 
  group_by(id) %>% 
  filter(if_all(a:b, ~ all(.x != 1)))

#      id     a     b
# 1     2     0     0
# 2     2     0     0
# 3     2     0     0
  • Related