Tidy eval now supports glue strings
So this works great:
my_summarise5 <- function(data, mean_var ) {
data %>%
mutate(
"mean_{{mean_var}}" := mean({{ mean_var }}),
)
}
mtcars %>% my_summarise5(cyl)
But then
my_summarise5 <- function(data, mean_var ) {
data %>%
mutate(
"mean_{{mean_var}}" := mean({{ mean_var }}),
"mean_{{mean_var}}_plusone" := "mean_{{mean_var}}"+1
)
}
mtcars %>% my_summarise5(cyl)
Throws
Error: Problem with `mutate()` input `mean_cyl_plusone`.
x non-numeric argument to binary
Would some 'paste' or 'glue' thing in the "mean_{{mean_var}}_plusone" := "mean_{{mean_var}}"+1
part fix this?
Note this is obviously not a useful case, its a MWE for the syntax. I actually want to define two new columns with different names, one which uses the other ... otherwise I have to repeat and it also gets messy.
Use across:
my_summarise5 <- function(data, mean_var ) {
data %>%
mutate(
"mean_{{mean_var}}" := mean({{ mean_var }}),
across(last_col(), ~.+1, .names = "{col}_plusone")
)
}
mtcars %>% my_summarise5(cyl) %>% head
giving:
mpg cyl disp hp drat wt qsec vs am gear carb mean_cyl mean_cyl_plusone
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6.1875 7.1875
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6.1875 7.1875
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 6.1875 7.1875
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 6.1875 7.1875
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 6.1875 7.1875
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 6.1875 7.1875
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With