R 获取函数的精确输入文本
我想得到函数参数的精确输入文本,并在输出中打印出来。例如,下面的函数将获取整数向量并返回它们的平方R 获取函数的精确输入文本,r,string,R,String,我想得到函数参数的精确输入文本,并在输出中打印出来。例如,下面的函数将获取整数向量并返回它们的平方 > my_func <- function(x) { + print(paste0("The square of ", toString(x), " is: ", toString(x^2))) + } > my_func(1:4) [1] "The square of 1, 2, 3, 4 is: 1, 4, 9, 16" 其中1:4正是函数的输入文本。my_func
> my_func <- function(x) {
+ print(paste0("The square of ", toString(x), " is: ", toString(x^2)))
+ }
> my_func(1:4)
[1] "The square of 1, 2, 3, 4 is: 1, 4, 9, 16"
其中
1:4
正是函数的输入文本。my_funcmy_func另一种方法是使用eval
parse
并将输入作为字符串传递
my_func <- function(x) {
print(paste0("The square of ", deparse(x), " is: ", toString(x^2)))
}
my_func <- function(x) {
cat("The square of ", x, " is: ", eval(parse(text = x))^2)
}
my_func("1:4")
#The square of 1:4 is: 1 4 9 16
my_func("3:6")
#The square of 3:6 is: 9 16 25 36
my_func另一种方法是使用eval
parse
并将输入作为字符串传递
my_func <- function(x) {
cat("The square of ", x, " is: ", eval(parse(text = x))^2)
}
my_func("1:4")
#The square of 1:4 is: 1 4 9 16
my_func("3:6")
#The square of 3:6 is: 9 16 25 36
my_func替代物是什么?对于我来说,似乎只使用deparse
,而不使用substitute()
将计算给定为x
的参数;在这种情况下,您甚至不需要deparse()
。如果要将未赋值表达式作为输入来处理,则需要这两个表达式,例如f(1+2)
或f(a+b)
@MikkoMarttila我倾向于认为参数将以最简化的格式给出。使用替换时,以下操作将失败:y=c(1:5,6:10);f(y)
但单独使用deparse
时,它将调用y,当差值为1时,它将输出为1:10@Onyambu我明白了,这很有趣!显然,deparse()
本身也很有用。我猜您是否需要替换取决于OP想要如何处理,例如f(1:4/2)
。替换是什么?对于我来说,似乎只使用deparse
,而不使用substitute()
将计算给定为x
的参数;在这种情况下,您甚至不需要deparse()
。如果要将未赋值表达式作为输入来处理,则需要这两个表达式,例如f(1+2)
或f(a+b)
@MikkoMarttila我倾向于认为参数将以最简化的格式给出。使用替换时,以下操作将失败:y=c(1:5,6:10);f(y)
但单独使用deparse
时,它将调用y,当差值为1时,它将输出为1:10@Onyambu我明白了,这很有趣!显然,deparse()
本身也很有用。我猜您是否需要替换取决于OP希望如何处理,例如f(1:4/2)
。