string 使用字符串作为函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7836972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use character string as function argument
提问by Kilian
I'm sure this is simple, but I cannot find a solution ... I would like to use a variable containing a character string as argument for a function.
我确定这很简单,但我找不到解决方案......我想使用一个包含字符串的变量作为函数的参数。
x <- c(1:10)
myoptions <- "trim=0, na.rm=FALSE"
Now, something like
现在,像
foo <- mean(x, myoptions)
should be the same as
应该是一样的
foo <- mean(x, trim=0, na.rm=FALSE)
Thanks in advance!
提前致谢!
回答by kohske
You can use eval
and parse
:
您可以使用eval
和parse
:
foo <- eval(parse(text = paste("mean(x,", myoptions, ")")))
回答by csgillespie
A more natural way to do what you want is to use do.call
. For example,
做你想做的更自然的方法是使用do.call
. 例如,
R> l[["trim"]] = 0
R> l[["na.rm"]] = FALSE
R> l[["x"]] = 1:10
##Or l <- list(trim = 0, na.rm = FALSE, x = 1:10)
R> do.call(mean, l)
[1] 5.5
If for some reason you really want to use a myoptions
string, you could always use strsplit
to coarce it into a list form. For example,
如果由于某种原因你真的想使用一个myoptions
字符串,你总是可以使用strsplit
将它压缩成一个列表形式。例如,
R> y = "trim=0, na.rm=FALSE"
R> strsplit(y, ", ")
[[1]]
[1] "trim=0" "na.rm=FALSE"
R> strsplit(y, ", ")[[1]][1]
[1] "trim=0"
回答by Soren Havelund Welling
Here's a third answer that both uses parse
, alist
and do.call
. My motivation for this new answer, is in the case where arguments are passed interactively from a client-side as chars. Then I guess, there is no good way around not using parse
. Suggested solution with strsplit
, cannot understand the context whether a comma ,
means next argument or next argument within an argument. strsplit
does not understand context as strsplit
is not a parser.
这是第三个答案,两者都使用parse
,alist
和do.call
。我对这个新答案的动机是在参数作为字符从客户端以交互方式传递的情况下。然后我想,不使用parse
. 建议的解决方案strsplit
, 无法理解逗号,
是指下一个参数还是参数中的下一个参数的上下文。strsplit
不理解上下文,因为strsplit
它不是解析器。
here arguments can be passed as "a=c(2,4), b=3,5"
or list("c(a=(2,4)","b=3","5")
这里的参数可以作为"a=c(2,4), b=3,5"
或list("c(a=(2,4)","b=3","5")
#' convert and evaluate a list of char args to a list of arguments
#'
#' @param listOfCharArgs a list of chars
#'
#' @return
#' @export
#'
#' @examples
#' myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
#' myArgs = callMeMaybe(myCharArgs)
#' do.call(mean,myArgs)
callMeMaybe2 = function(listOfCharArgs) {
CharArgs = unlist(listOfCharArgs)
if(is.null(CharArgs)) return(alist())
.out = eval(parse(text = paste0("alist(",
paste(parse(text=CharArgs),collapse = ","),")")))
}
myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
myArgs = callMeMaybe2(myCharArgs)
do.call(mean,myArgs)
[1] 2