I want to create a function that takes up as the first argument the name of a data set, and as a second argument, part of a column's name from the dataframe. I then want to use glue
to dynamically construct the column name, in the function, and use that column in a mutate
call, like so:
library(tidyverse)
tmp <-
function(data, type){
var <- glue::glue("Sepal.{type}")
iris |>
select({{var}}) |>
mutate("{var}" := mean({{var}}))
}
I've tried a lot of things, but I struggle to find a solution where the column is called both for the name of the new column (here, "{var}"
) and for the computation of the new column (here, mean({{var}})
). What should one do in such cases?
Here, calling tmp(iris, "Length")
should return a 150x1
data.frame with the mean value in all rows.
tidyverse
solution are preferred, or any pipe-based answers.
.data
pro-noun, i.e.mutate("{var}" := mean(.data[[var]]))
– Dobb{{}}
does not work directly here, despite being sometimes used as examples in the documentation: dplyr.tidyverse.org/articles/programming.html – Stuccovar
refers to a character string, not a symbol. In some cases this seems to work with{{…}}
but not in all. Which honestly is pretty confusing and I’d wish that{{…}}
was more strict/consistent in what it accepted. – Steinbok