Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dplyr - Filter if any variable is equal to a value

Tags:

r

dplyr

I have a dataset a with 5 variables and want to filter it like this:

a1 <- a %>% filter(var_1 != 1 , var_2 != 1 , var_3 != 1 , var_4 != 1 , variable_5 != 1)

I was wondering if anything like this (pseudo code) existed:

a1 <- a %>% filter(anyvariable != 1)

In other words I would like to get rid of all the rows with value 1, no matter where it appears. 1 is just a random number. It could have been 9, 99, or whatever else! Thanks!

like image 803
Gaspare Avatar asked May 21 '16 13:05

Gaspare


People also ask

How do I filter multiple variables in R?

In this, first, pass your dataframe object to the filter function, then in the condition parameter write the column name in which you want to filter multiple values then put the %in% operator, and then pass a vector containing all the string values which you want in the result.

What does filter () do R?

The filter() method in R is used to subset a data frame based on a provided condition. If a row satisfies the condition, it must produce TRUE . Otherwise, non-satisfying rows will return NA values. Hence, the row will be dropped.


1 Answers

We might be able to use rowSums

a %>% 
  filter(rowSums(. !=0) >0)
#    Col1 Col2
#1    1    1
#2    0   24
#3    9    1

If I change it to !=1

a %>% 
   filter(rowSums(. != 1) > 0)
#   Col1 Col2
#1    0   24
#2    9    1
#3    0    0

Note that this will remove the rows with all 1s. In the previous case, it removes the rows with all 0s which is consistent with what the OP mentioned in the post.

Update

If the OP wants to remove rows with any 1 (just a number, he can use 9, or 99, or 999)

a %>% 
   filter(!rowSums(.==1))
#    Col1 Col2
#1    0   24
#2    0    0

data

a <- data.frame(Col1 = c(1, 0, 9, 0), Col2 = c(1, 24, 1, 0))
like image 95
akrun Avatar answered Oct 21 '22 06:10

akrun