2

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?

2
  • function(df, x) df[!is.na(df[[x]]), ]
    – Hong Ooi
    Aug 11, 2017 at 1:56
  • 2
    If you're providing a string as the column name, you're using standard evaluation and can skip the whole tidyeval business.
    – Hong Ooi
    Aug 11, 2017 at 1:57

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

3

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))))

}
2
  • Very helpful to refer to rlang; I had seen the quosure stuff for dplyr but rlang::sym looks like a straightforward way to transition functions that use the old style e.g. mutate_ calls to quosures.
    – mikeck
    Aug 11, 2017 at 5:23
  • dplyr will soon export sym() as well. The functionalities of sym() and quosures are complementary. Aug 11, 2017 at 7:13
1

There is a good write-up on how to do things like this in dplyr here: http://dplyr.tidyverse.org/articles/programming.html

The punchline for this case is that you don't have to quote a in the parameters. You can also use !! instead of UQ

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(!!enquo_name)))

}
1
  • I wouldn't call that variable column_name because "column names" makes me think of strings, e.g. the output of colnames(). Also in your version it's not necessarily a column symbol, it could be an expression too. Aug 11, 2017 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.