mbkm
mbkm

Reputation: 78

How to filter multiple columns using a single critera

I have

       4  5  6  7
1      3  3  3  3
2      1  2  2  1
3      2  1  1 NA
4      2  7  1 NA
5      1  1  1  1

I want to filter rows with either 2 or 3 in columns 1 to 4 so I only get rows 1,2,4

I tried

df1%>%filter_at(vars(4:7), all_vars(c(2,3)) -> df2

which returns

Error in filter_impl(.data, quo) : Result must have length 413, not 2

and

filter(d1[4:7]%in%c(1,3))

which returns

Error in filter_impl(.data, quo) : Result must have length 413, not 4

I want to avoid using

df1%>%filter(rowname1%in%c(1,3)|rowname1%in%c(1,3)| ...)

I dont get the syntax. Thanks

Upvotes: 1

Views: 63

Answers (1)

www
www

Reputation: 39154

We can use any_vars and %in% to achieve this task.

library(dplyr)

df1 %>% filter_at(vars(1:4), any_vars(. %in% c(2, 3)))
#   X4 X5 X6 X7
# 1  3  3  3  3
# 2  1  2  2  1
# 3  2  1  1 NA
# 4  2  7  1 NA

Or use == with |.

df1 %>% filter_at(vars(1:4), any_vars(. == 2 | . == 3))
#   X4 X5 X6 X7
# 1  3  3  3  3
# 2  1  2  2  1
# 3  2  1  1 NA
# 4  2  7  1 NA

DATA

df1 <- read.table(text = "       4  5  6  7
1      3  3  3  3
2      1  2  2  1
3      2  1  1 NA
4      2  7  1 NA
5      1  1  1  1",
                  header = TRUE, stringsAsFactors = FALSE)

Upvotes: 1

Related Questions