r - concatenate quosures and string -


i'm looking way concatenate quosure , string result quosure. actually, if use paste0() , quo_name(), can it. wonder if there more elegant alternative write function in package. generic example:

library(dplyr)  df <- data_frame(   z_1 = 1,   z_2 = 2,   y_1 = 10,   y_2 = 20 )  get_var <- function(.data, var) {   xx = enquo(var)    select(.data, paste0(quo_name(xx), "_1"), paste0(quo_name(xx), "_2")) }  get_var(df, z) # tibble: 1 x 2     z_1   z_2   <dbl> <dbl> 1     1     2 

without function, how using dplyr:

library(dplyr) df %>%   select(starts_with("z_")) 

you can create function , pass in string variable name this:

get_var= function(df, var){   df %>%     select(starts_with(paste0(var, "_"))) }  get_var(df, "z") 

now, tricky part comes when trying pass in variable name without quoting function (the r code, not value contains). 1 way of doing deparse + substitute in base r. converts symbol supplied var string, convenient later use within function:

get_var = function(df, var){   var_quo = deparse(substitute(var))   df %>%     select(starts_with(paste0(var_quo, "_"))) } 

finally, here how same enquo , quo_name in rlang/tidyverse package:

library(rlang) get_var = function(df, var){   var_quo = quo_name(enquo(var))   df %>%     select(starts_with(paste0(var_quo, "_"))) }  get_var(df, z) get_var(df, y) 

result:

# tibble: 1 x 2     z_1   z_2   <dbl> <dbl> 1     1     2  # tibble: 1 × 2     y_1   y_2   <dbl> <dbl> 1    10    20 

notes:

  1. quosures quoted expressions keep track of environment.
  2. enquo takes symbol referring function's argument, quotes r code , bundles function's environment in quosure.
  3. quo_name formats quosure string, can used later in function.
  4. quo_text similar quo_name not check whether input symbol.

check these:

  1. rlang documentation
  2. non-standard evaluation in r
  3. ?enquo
  4. ?quo_name

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -