mickmcq
mickmcq

Reputation: 43

Why is a tidyverse function erroring out when the function contents work?

The following code fails with an error message "Error in .f(.x[[i]], ...) : object 'area' not found "

Yet it works if I enter the function contents manually.

library(tidyverse)
df <- data.frame(
       'id'=1:10,
       'inp'=c(1,1,1,2,2,3,3,7,8,7),
       'out'=c(3,3,3,2,2,4,4,9,8,9),
       'area'=c('A','A','A','A','A','A','B','B','B','C')
      )

uniqdashc <- function(x,y) {
    x %>%
        select(y) %>%
        group_by(y) %>%
        dplyr::mutate(count=n()) %>%
        unique() %>%
        arrange(desc(count))
}
uniqdashc(df,area)

Upvotes: 1

Views: 36

Answers (2)

akrun
akrun

Reputation: 886928

As it is unquoted, we can use {{}} for evaluation. It does the enquo + !!

uniqdashc <- function(x,y) {
   x %>%
    select({{y}}) %>%
    group_by({{y}}) %>%
    dplyr::mutate(count=n()) %>%
    distinct %>%
    arrange(desc(count))
  }

testing

uniqdashc(df, area)
# A tibble: 3 x 2
# Groups:   area [3]
#  area  count
#  <fct> <int>
#1 A         6
#2 B         3
#3 C         1

We show why the error occurred by first posting the {{}}. Of course, it can be simplified, but here the question is about why the error occurs


Here, is another variation where the user can either pass quoted or unquoted

uniqdashc <- function(x,y) {
   x %>%
      count(!! rlang::ensym(y), sort = FALSE) 
  }


uniqdashc(df, area)
# A tibble: 3 x 2
#  area      n
#  <fct> <int>
#1 A         6
#2 B         3
#3 C         1

uniqdashc(df, "area")
# A tibble: 3 x 2
#  area      n
#  <fct> <int>
#1 A         6
#2 B         3
#3 C         1

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388797

You could try non-standard evaluation and in your case, the code can be reduced to

library(dplyr)

uniqdashc <- function(x, y) x %>% count({{y}}, sort = TRUE)
uniqdashc(df, area)

# A tibble: 3 x 2
#  area      n
#  <fct> <int>
#1 A         6
#2 B         3
#3 C         1

Upvotes: 0

Related Questions