How to make a filter based on a condition?

Asked

Viewed 26 times

2

I have a date.frame with two columns (CLASSWK and IND) and I’d like to apply a filter based on one condition, but I’m unable to do that.

I have a column CLASSWK, that I only want to keep values that are 1 or 2. But this only applies if my other column, IND, is different from 0.

So, basically, if IND == 0, I just disregard my filter, but if mine IND is any other value, so I have to apply the filter in the column CLASSWK and remove values that are different from 1 or 2.

Man dput:

structure(list(CLASSWK = c(1, 2, 1, 3, 5, 1, 2, 6, 7, 3), IND = c(1, 
2, 3, 4, 0, 6, 0, 0, 8, 4)), class = "data.frame", row.names = c(NA, 
-10L))

Code I tried to use:

library(dplyr)

x %>%
  filter(case_when(IND != 0 & CLASSWK == 1 & CLASSWK == 2))

1 answer

3


Here’s a way with the package dplyr.
Like CLASSWK can take various values used %in% and not equality.

library(dplyr)

x %>% filter((CLASSWK %in% 1:2 & IND != 0) | IND == 0)
#  CLASSWK IND
#1       1   1
#2       2   2
#3       1   3
#4       5   0
#5       1   6
#6       2   0
#7       6   0

In R base, any of the following ways also solves the problem.

subset(x, (CLASSWK %in% 1:2 & IND != 0) | IND == 0)
x[(x$CLASSWK %in% 1:2 & x$IND != 0) | x$IND == 0, ]
  • but in both cases I am removing from the basis the values where IND == 0 and I’d like to keep them too.

  • @Alexandresanches Done, see now.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.