rdplyrtidyversense

Alternatives to deparse(substitute()) to get name of object within a function


In vignette("programming", package = "dplyr") there is the following example code

my_summarise2 <- function(data, expr) {
  data %>% summarise(
    mean = mean({{ expr }}),
    sum = sum({{ expr }}),
    n = n()
  )
}

I want to adapt this so the name of the expr object is included in the output, and I can do that using deparse(substitute(())

my_summarise2 <- function(data, expr) {
  exprname = deparse(substitute(expr))
  data %>% summarise(
    var = exprname,
    mean = mean({{ expr }}),
    sum = sum({{ expr }}),
    n = n()
  )
}

my_summarise2(iris, Petal.Width)

#          var     mean   sum   n
#1 Petal.Width 1.199333 179.9 150

Is there another tidyverse-recommended way to achieve the same result?


Solution

  • We can use rlang::enquo and rlang::as_name:

    library(dplyr)
    
    my_summarise3 <- function(data, expr) {
      exprname = rlang::as_name(rlang::enquo(expr))
      data %>% summarise(
        var = exprname,
        mean = mean({{ expr }}),
        sum = sum({{ expr }}),
        n = n()
      )
    }
    
    my_summarise3(iris, Petal.Width)
    #>           var     mean   sum   n
    #> 1 Petal.Width 1.199333 179.9 150
    

    Or using rlang::enexpr and rlang::as_label:

    library(dplyr)
    
    my_summarise3 <- function(data, expr) {
      exprname = rlang::as_label(rlang::enexpr(expr))
      data %>% summarise(
        var = exprname,
        mean = mean({{ expr }}),
        sum = sum({{ expr }}),
        n = n()
      )
    }
    
    my_summarise3(iris, Petal.Width)
    #>           var     mean   sum   n
    #> 1 Petal.Width 1.199333 179.9 150
    

    Created on 2025-03-13 with reprex v2.1.1