Andy
Andy

Reputation: 149

Why can my function not find the variable that I input into it?

So when cleaning data I have to apply a function that removes all rows in which a certain column ends with the string "Total".

I tried to apply it the str_detect to all columns, but it did not work.

Then, I thought I would create a function. I'm also in the process of learning to get better at creating functions. But I can somehow not wrap my head around them. The normal code looks like this:

D3 <- D3 %>%
   dplyr::filter(!stringr::str_detect(institution, "Total$"))

I have several variables, where institution is supposed to be. So I wrote this function:

remove_total <- function(data, x) {
   data %>% 
     dplyr::filter(!stringr::str_detect(x, "Total$"))
 }

Then when I try to run it, the following appears:

remove_total(D3, institution)

! Problem with filter() input ..1. i Input ..1 is !stringr::str_detect(x, "Total$"). x object 'institution' not found

When I run rlang::last_trace(), I get this:

! Problem with filter() input ..1. i Input ..1 is !stringr::str_detect(x, "Total$"). x object 'institution' not found Backtrace:

  1. global remove_total(D3, institution)
  2. base::.handleSimpleError(...)
  3. dplyr h(simpleError(msg, call))

What am I doing wrong?

Thank you

Upvotes: 2

Views: 703

Answers (1)

akrun
akrun

Reputation: 887691

If we pass unquoted variables, use curly-curly operator ({{}}) to evaluate

remove_total <- function(data, x) {
   data %>% 
     dplyr::filter(!stringr::str_detect({{x}}, "Total$"))
 }

-testing

remove_total(D3, institution)

If there are many variables, use if_any/if_all (for removing rows where are any column having the substring or all the columns respectively)

D3 %>%
    filter(!if_any(cols_of_interest, ~ str_detect(.x, "Total$")))

Upvotes: 2

Related Questions