Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate function argument as string within dplyr custom function

Tags:

r

dplyr

tidyeval

I am writing a custom function that outputs the mean and sd of a field. I would like the .field argument to be evaluated in a tidyeval manner at some states and as a string at another stage. How can I evaluate the .field argument as a string?

library(dplyr)
library(tidyr)

mean_sd <- function(.data, .field){
    .data %>% 
    summarise(
        mean = mean({{.field}}), 
        sd = sd({{.field}})
    ) %>% 
    pivot_longer(
        everything(),
        names_to = "stat",
        values_to = '.field' # I'd like this to print the value of .field
        ) %>% 
    mutate(across(is.numeric, ~round(.x, 2)))
}

mean_sd(mtcars, mpg)

enter image description here

like image 391
Joe Avatar asked Jun 16 '26 12:06

Joe


2 Answers

We can use rlang::englue() and use the curly curly operator inside:

library(dplyr)
library(tidyr)

mean_sd <- function(.data, .field){
  .data %>% 
    summarise(
      mean = mean({{.field}}), 
      sd = sd({{.field}})
    ) %>% 
    pivot_longer(
      everything(),
      names_to = "stat",
      values_to = rlang::englue("{{ .field }}")
    ) %>% 
    mutate(across(where(is.numeric), ~round(.x, 2)))
}

mean_sd(mtcars, mpg)

#> # A tibble: 2 × 2
#>   stat    mpg
#>   <chr> <dbl>
#> 1 mean  20.1 
#> 2 sd     6.03

Created on 2023-03-28 with reprex v2.0.2

like image 198
TimTeaFan Avatar answered Jun 18 '26 03:06

TimTeaFan


Besides the more elegant rlang::englue another option would be to use as_label(enquo(x)):

library(dplyr, warn.conflicts = FALSE)
library(tidyr)

mean_sd <- function(.data, .field) {
  .data %>%
    summarise(
      mean = mean({{ .field }}),
      sd = sd({{ .field }})
    ) %>%
    pivot_longer(
      everything(),
      names_to = "stat",
      values_to = as_label(enquo(.field))
    ) %>%
    mutate(across(where(is.numeric), ~ round(.x, 2)))
}

mean_sd(mtcars, mpg)
#> # A tibble: 2 × 2
#>   stat    mpg
#>   <chr> <dbl>
#> 1 mean  20.1 
#> 2 sd     6.03
like image 38
stefan Avatar answered Jun 18 '26 01:06

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!