I want to write a simple function that takes a dataframe and a numeric column (a parameter e.g. called col
as input. The name of the numeric column should be quoted (like "mpg"
). I am having some troubles figuring out how I could use the scales::rescale
-function to map the value of the column (whos name is stored in col
) to a new interval (e.g. 0 to 1).
I know this works
library(dplyr)
df = data.frame(val = sample(1:10, 5, replace = T))
resc = function(df, col){
df %>%
mutate(
rescaled_value = scales::rescale(.data[[col]])
)
}
But I wanted to do something like this:
resc = function(df, col){
df %>%
mutate(
rescaled_value = scales::rescale({{col}}, to=c(0,1), from=range(.data[[col]]))
)
}
So basically I do not know how to specify the first paramter to the rescale
-function in a way that works in tidy eval.
Use !!sym like this:
resc = function(df, col){
df %>%
mutate(
rescaled_value = scales::rescale(!!sym(col), from = range(!!sym(col)))
)
}
This also works and is short but does not use tidy eval. It depends on using %>% and would not work with |> .
resc = function(df, col){
df %>%
mutate(
rescaled_value = scales::rescale(.[[col]], from = range(.[[col]]))
)
}