0
library(nycflights13)
library(dplyr)
sum.na <- function(df,x){df %>% summarise(n=sum(is.na(x)))}
sum.na(flights, arr_time)

When I run the above code, I get the error below:

  **Error in eval(cols[[col]], .data, parent.frame()) : 
  object 'arr_time' not found**
Sam Firke
  • 19,406
  • 8
  • 78
  • 89
Ram
  • 1

2 Answers2

1

Use curly-curly ({{}}) to pass column names as function argument.

library(nycflights13)
library(dplyr)

sum.na <- function(df,x){df %>% summarise(n=sum(is.na({{x}})))}

sum.na(flights, arr_time)
# A tibble: 1 x 1
#      n
#  <int>
#1  8713
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
0

We can also use ensym with !!

library(nycflights13)
library(dplyr)
sum.na <- function(df, x) { 
                 df %>%
                   summarise(n = sum(is.na(!! ensym(x))))
   }

 

It can take both quoted as well as unquoted

 sum.na(flights, arr_time)
 # A tibble: 1 x 1
 #     n
 # <int>
 #1  8713

 sum.na(flights, 'arr_time')
# A tibble: 1 x 1
#      n
#  <int>
#1  8713
akrun
  • 789,025
  • 32
  • 460
  • 575