Search code examples
rdplyrrlangtidyeval

How to programmatically filter columns in dplyr?


How would I create a function that drops NA values in a column if I don't want to specify the column until the function is called?

minimal_case <- function(column_name = "a") {
  enquo_name <- enquo(column_name)

  example <- tibble(a = c(NA, 1))

  print(filter(example, !is.na(a)))

  print(filter(example, !is.na(rlang::UQ(enquo_name))))

}

The output of the first print statement is:

# A tibble: 1 x 1
      a
  <dbl>
1     1

The output of the second print statement is:

# A tibble: 2 x 1
      a
  <dbl>
1    NA
2     1

How do I get the second print statement to match the first?


Solution

  • It seems the column_name parameter is a string. In that case, you can use rlang::sym:

    minimal_case <- function(column_name = "a") {
        example <- tibble(a = c(NA, 1))
    
        print(filter(example, !is.na(a)))
    
        print(filter(example, !is.na(!!rlang::sym(column_name))))
    
    }