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:
- quosures quoted expressions keep track of environment.
enquotakes symbol referring function's argument, quotes r code , bundles function's environment in quosure.quo_nameformats quosure string, can used later in function.quo_textsimilarquo_namenot check whether input symbol.
check these:
rlangdocumentation- non-standard evaluation in r
?enquo?quo_name
Comments
Post a Comment