Search code examples
rstringrrlang

str_subset with curly curly in R


I've a small function to read in files with certain string using str_subset which works if I pass the argument in quotes but I want to able to do it without. I thought I could do this with curly curly but isn't working.

Working example passing with quotes:

#creating csv file
library(tidyverse)
write_csv(mtcars, "C:\\Users\\testSTACK.csv")


#reading function
read_in_fun <- function(x) {

  setwd("C:\\Users")
  d <- list.files()   #lists all files in folder
  file <- d %>% 
    str_subset(pattern = x)

  #read in
  df <- read_csv(file)

  arg_name <- deparse(substitute(x)) 
  var_name <- paste("df_new", arg_name, sep = "_") 
  assign(var_name, df, env = .GlobalEnv) 

}

read_in_fun("STACK")

#this works, returns df called:
df_new_"STACK"

now if i try to be able to pass with no quotes using curly curly approach:

read_in_fun <- function(x) {

  setwd("C:\\Users")
  d <- list.files()   #lists all files in folder
  file <- d %>% 
    str_subset(pattern = {{x}})

  #read in
  df <- read_csv(file)

  arg_name <- deparse(substitute(x)) 
  var_name <- paste("df_new", arg_name, sep = "_") 
  assign(var_name, df, env = .GlobalEnv) 

}
read_in_fun(STACK)
#Error in type(pattern) : object 'STACK' not found

also tried using enquo

read_in_fun <- function(x) {

  x_quo <- enquo(x)


  setwd("C:\\Users")
  d <- list.files()   #lists all files in folder
  file <- d %>% 
    str_subset(pattern = !! as_label(x_quo)) #OR !!(x_quo)

  #read in
  df <- read_csv(file)

  arg_name <- deparse(substitute(x)) 
  var_name <- paste("df_new", arg_name, sep = "_") 
  assign(var_name, df, env = .GlobalEnv) 

}
read_in_fun(STACK)
# Error during wrapup: Quosures can only be unquoted within a quasiquotation context.

My desired output is a df called df_new_STACK. Can curly curly be used in this way? Thanks


Solution

  • Using ensym should work.

    read_in_fun <- function(x) {
    
      x_sym <- ensym(x)
    
      d <- list.files()   
      file <- d %>% 
        str_subset(pattern = as_label(x_sym)) 
    
      #read in
      df <- read_csv(file)
    
      arg_name <- deparse(substitute(x)) 
      var_name <- paste("df_new", arg_name, sep = "_") 
      assign(var_name, df, env = .GlobalEnv) 
    
    }
    
    read_in_fun(STACK)
    
    df_new_STACK