I'm learning more about programming with R but I'm puzzled as to the behavior below. Essentially minor changes/variations in the code can produce different results. Any thoughts on why no named argument example below doesn't return the consistent results?
library(tidyverse)
library(rlang)
test <- function(.data, ...) {
cols <- rlang::enexprs(...)
mtcars %>%
reframe(
!!!cols
)
}
test(
median(mpg),
mean(vs)
)
test <- function(.data,...){
cols <- rlang::enexprs(...)
mtcars %>%
reframe(
!!!cols
)
}
test(
median=median(mpg)
,mean=mean(vs)
)
test <- function(.data, ...) {
cols <- rlang::enexprs(...)
.data %>%
reframe(
!!!cols
)
}
test(
mtcars,
median(mpg),
mean(vs)
)
As Jaret Mamrot already suggests in the comments, the problem is in your .data
arg. Either drop it as suggested by Jaret or use it. In either case named arguments are working fine:
library(tidyverse)
library(rlang)
test <- function(.dat, ...) {
cols <- rlang::enexprs(...)
.dat %>% # <- here we actually use the .data arg
reframe(
!!! cols
)
}
test(mtcars,
median(mpg),
mean(vs)
)
#> median(mpg) mean(vs)
#> 1 19.2 0.4375
test(mtcars,
median = median(mpg),
mean = mean(vs)
)
#> median mean
#> 1 19.2 0.4375
Created on 2023-07-25 with reprex v2.0.2