Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming a new variable based on a quosure

I'm trying to write a custom function that will compute a new variable based on values from a predefined vector of variables (e.g., vector_heavy) and then name the new variable based on an argument provided to the function (e.g., custom_name).

This variable naming is where my quosure skills are failing me. Any help is greatly 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 reads:

Error: unexpected '=' in:
"    rowwise() %>% 
    mutate(!!cv_name ="

Removing the !! before cv_name within mutate() will result in a function that calculates a new variable literally named cv_name, and ignoring the custom_name I've 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 get this function to utilize the custom_name I supply as an argument for cv_name?

like image 923
Joe Avatar asked Jul 03 '17 20:07

Joe


1 Answers

You need to use the := helper within mutate. You'll also need quo_name to convert the input to a string.

The mutate line of your function will then look like

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

In its entirety:

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
like image 134
aosmith Avatar answered Nov 07 '22 00:11

aosmith