Naming a new variable based on quosure

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 ?

+7
r dplyr tidyverse rlang
source share
1 answer

You need to use helper := within mutate . You will also need quo_name to convert input to string.

The mutate line of your function will look like this:

mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE))

Generally:

 cv_compute <- function(data, cv_name, cv_vector){ cv_name <- enquo(cv_name) data %>% rowwise() %>% mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE)) %>% ungroup() } cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy) mpg cyl disp hp drat wt qsec vs am gear carb custom_name <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 56.20667 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 56.29167 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 38.10667 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 89.07167 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 123.81333 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 78.15333 
+7
source share

All Articles