Ok so here's my imaginary data.frame called data
A1 A2 A3 A4 A5 A6
1 2 45 35 33 38
5 1 23 33 58 47
18 26 78 15 5 6
What I want do is select all rows that have a 1 or 33 in any of the columns
so my initial thought was to write the following code
a <- paste0("A",1:6)
num <- c("1","33")
data <- data %>%
filter(a %in% num)
intuitively I though this would work but I keep getting the error Result must have length _ not _.
Any way I could get around this or use a different solution? Thanks!
We can do this with filter_all
library(dplyr)
data %>%
filter_all(any_vars(. %in% c(1, 33)))
# A1 A2 A3 A4 A5 A6
#1 1 2 45 35 33 38
#2 5 1 23 33 58 47
If we need to do this on a subset of columns use filter_at and specify the column index or nameswithin vars
data %>%
filter_at(vars(matches("A\\d+")), any_vars(. %in% c(1, 33)))
The vars can also take objects
a <- paste0("A", 1:6)
vals <- c(1, 33)
data %>%
filter_at(vars(a), any_vars(. %in% vals))
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