str_subset 在 R 中使用卷曲卷曲

str_subset with curly curly in R

我有一个小函数,可以使用 str_subset 读取具有特定字符串的文件,如果我在引号中传递参数但我希望能够在没有引号的情况下执行此操作。我以为我可以用 curly curly 做到这一点,但没有用。

带引号传递的工作示例:

#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"

现在,如果我尝试使用 curly curly 方法能够不带引号通过:

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

也尝试使用 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.

我想要的输出是一个名为 df_new_STACKdf。 curly卷曲可以这样用吗?谢谢

使用 ensym 应该可以。

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