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
  • 21,571
  • 9
  • 87
  • 105
Ram
  • 1
  • Use : `sum.na <- function(df,x){df %>% summarise(n=sum(is.na({{x}})))}` – Ronak Shah Feb 18 '21 at 13:08
  • still getting same error – Ram Feb 18 '21 at 13:12
  • Does this answer your question? [Use variable names in functions of dplyr](https://stackoverflow.com/questions/24569154/use-variable-names-in-functions-of-dplyr) – Sam Firke Feb 18 '21 at 17:03
  • Programming with dplyr has changed a lot over time, so there are some obsolete answers there. Try this one specifically: https://stackoverflow.com/a/56830842 – Sam Firke Feb 18 '21 at 17:05

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
  • 377,200
  • 20
  • 156
  • 213
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
  • 874,273
  • 37
  • 540
  • 662