I am trying to write a user-defined function that will compute a new variable based on values ββfrom a predefined vector of variables (e.g. vector_heavy) and then call a new variable based on the argument provided to the function (e.g. custom_name).
This variable name is where my quosure skills fail. Any help is appreciated.
library(tidyverse) vector_heavy <- quos(disp, wt, cyl) cv_compute <- function(data, cv_name, cv_vector){ cv_name <- enquo(cv_name) data %>% rowwise() %>% mutate(!!cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>% ungroup() } d <- cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)
My error message:
Error: unexpected '=' in: " rowwise() %>% mutate(!!cv_name ="
Removal !! before cv_name inside mutate() will lead to a function that evaluates a new variable, literally named cv_name , and ignoring custom_name , which I included as an argument.
cv_compute <- function(data, cv_name, cv_vector){ cv_name <- enquo(cv_name) data %>% rowwise() %>% mutate(cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>% ungroup() }
How can I force this function to use the custom_name I supply as an argument to cv_name ?
r dplyr tidyverse rlang
Joe
source share