英文:
Addition quotations around an R function input?
问题
你可以使用以下方式在R中给函数输入加上引号:
function_name <- function(x) {
paste0("The input you have chosen is '", x, "'")
}
# 调用函数并传入参数
result <- function_name(x = "gender")
# 输出: "The input you have chosen is 'gender'"
这段代码会将输入的参数 x
包裹在单引号中,生成你想要的输出。
英文:
How do I add quotations around an input to a function in R?
I would like to have something such as,
function_name (x) {
paste0("The input you have chosen is", x,)
}
function_name(x = gender)
output: "The variable you have chosen is gender"
I know that I could do it using paste0 if the input was
function_name("gender")
, but I don't know how to do this if the input doesn't have quotations.
I have tried using paste0 to paste single quotations around the word, but gives errors such as:
> Error in paste0("'", x, "'") : object 'Gender' not found.
I have also tried escaping the quotation marks, but the slashes are being read and giving errors as well.
Thanks in advance for any suggestions.
答案1
得分: 3
只需用substitute
函数包装参数。这样可以进行非标准评估(NSE):
function_name <- function (x) {
paste0("你选择的输入是", substitute(x)) #注意这里
}
现在你可以运行:
function_name(gender) # 不使用引号
[1] "你选择的输入是 gender"
function_name("gender") # 使用引号
[1] "你选择的输入是 gender"
英文:
Just wrap the parameter with substitute
function. This enables one to NSE:
function_name <- function (x) {
paste0("The input you have chosen is ", substitute(x)) #Note here
}
And now you can run:
function_name(gender) # Without quotes
[1] "The input you have chosen is gender"
function_name("gender") # With quotes
[1] "The input you have chosen is gender"
答案2
得分: 1
As pointed by AdroMine, this envolves non-standard evaluation. The link he provided is quite useful.
But to provide an answer, you can do the following:
function_name <- function(x) {
paste("The input you have chosen is", as.character(rlang::enexpr(x)))
}
function_name(x = gender)
[1] "The input you have chosen is gender"
We are capturing the "word" gender
before R tries to evaluate it (i.e., tries to find which value should be associated with gender
), and then, we are getting the actual text with as.character()
英文:
As pointed by AdroMine, this envolves non-standard evaluation. The link he provided is quite useful.
But to provide an answer, you can do the following:
function_name <- function(x) {
paste("The input you have chosen is", as.character(rlang::enexpr(x)))
}
function_name(x = gender)
[1] "The input you have chosen is gender"
We are capturing the "word" gender
before R tries to evaluate it (i.e., tries to find which value should be associated with gender
), and then, we are getting the actual text with as.character()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论