我有一个函数可以刷新从DB传递的新变量(在某些条件下)。如果不满足条件集,则返回值本身就是变量而没有变化。条件并不重要,但是在名称上传递带引号的变量的方法就是麻烦。有没有办法在没有引号的情况下传递参数。
考虑下面的玩具功能ref
。我们需要将变量直接作为参数传递。目前,只有将变量名称作为字符向量传递时,此函数才有效。
abc=55
wxy=44
ref<-function(variable_name=NULL){
if(exists(variable_name))
{
updated_df = switch(variable_name,
"abc"=paste("Variable1:",variable_name,get(variable_name)),
"wxy"=paste("Variable2:",variable_name,get(variable_name)),
"NOT FOUND")
} else stop("passed variable does not exist")
if(updated_df=="NOT FOUND") updated_df = get(variable_name)
updated_df
}
类似但不相同的问题是here。它没有帮助。
答案 0 :(得分:5)
1)使用deparse(substitute(x))
获取名称。没有包使用。
ref <- function(variable) {
name <- deparse(substitute(variable))
cat("name:", name, "value:", variable, "\n")
}
# test
abc <- 55
ref(abc)
## name: abc value: 55
2)另一种可能性是传递公式:
ref2 <- function(formula) {
name <- all.vars(formula)[1]
variable <- get(name, environment(formula))
cat("name:", name, "value:", variable, "\n")
}
# test
abc <- 55
ref2(~ abc)
## name: abc value: 55
答案 1 :(得分:2)
我们可以使用enquo/quoname
rlang
ref <- function(variable_name=NULL){
variable_name <- rlang::quo_name(rlang::enquo(variable_name))
if(exists(variable_name)){
updated_df = switch(variable_name,
"abc"=paste("Variable1:",variable_name,get(variable_name)),
"wxy"=paste("Variable2:",variable_name,get(variable_name)),
"NOT FOUND")
} else stop("passed variable does not exist")
if(updated_df=="NOT FOUND") updated_df = get(variable_name)
updated_df
}
ref(abc)
#[1] "Variable1: abc 55"
除了上述更改之外,我们还可以在quosure上使用eval_tidy
将get
和glue
替换为paste
ref <- function(variable_name=NULL){
vname <- enquo(variable_name)
variable_name <- rlang::quo_name(vname)
if(exists(variable_name)){
updated_df = switch(variable_name,
"abc"= glue::glue("Variable1: {variable_name} {rlang::eval_tidy(vname)}"),
"wxy"= glue::glue("Variable2: {variable_name} {rlang::eval_tidy(vname)}"),
"NOT FOUND")
} else stop("passed variable does not exist")
if(updated_df=="NOT FOUND") updated_df = vname
updated_df
}
ref(abc)
#[1] "Variable1: abc 55"