我有一个很小的函数,可以使用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"现在,如果我尝试使用卷曲方法传递无引号:
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_STACK的df。curly curly可以这样使用吗?谢谢
发布于 2020-06-20 06:25:07
使用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_STACKhttps://stackoverflow.com/questions/61015854
复制相似问题