1

I am trying to write a function that uses dplyr's filter_at. My dataset includes columns named pr1:pr15 (all chr variables with values such as "8201" or "0599"), and I am trying to build a filter that includes any row that has a value x in any col p1:pr15

This is what I've tried: my_filterfunc <- function(data, x) {data %>% filter_at(vars(starts_with(regex("pr[0:9]"))), any_vars(. == "x"))}

When I try to run this function as such: test <- my_fiterfunc(my_tibble, x = "8201")

I get an error: Error: .predicate has no matching columns Even though I know that there are matching columns

Maya Harary
  • 417
  • 1
  • 4
  • 7

1 Answers1

2

We don't need quote around 'x' and also it is easier to work with matches

my_filterfunc <- function(data, x) {
data %>% 
   filter_at(vars(matches("^pr\\d+")), any_vars(. == x))
 }

my_filterfunc(df1, "8201")
#  ID  pr1  pr2  pr3  pr4  pr5  pr6  pr7  pr8  pr9 pr10
#1  3 8211 8212 8211 8201 8211 8209 8206 8210 8205 8206
#2  5 8210 8204 8205 8203 8204 8201 8215 8215 8201 8206

data

set.seed(24)
df1 <- data.frame(ID = 1:5, matrix(sample(as.character(8201:8215), 5*10, replace = TRUE),
                 5, 10, dimnames = list(NULL, paste0("pr", 1:10))), stringsAsFactors = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662