r - Alternatives to deparse(substitute()) to get name of object within a function - Stack Overflow

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

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?

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?

Share Improve this question edited Mar 13 at 18:41 zephryl 17.7k4 gold badges16 silver badges34 bronze badges asked Mar 13 at 17:52 moreQthanAmoreQthanA 8512 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744686906a4587973.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信