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!
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.
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.
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.
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
a <- data.frame(Col1 = c(1, 0, 9, 0), Col2 = c(1, 24, 1, 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With