使用字符串作为函数参数
我确信这很简单,但我找不到解决方案...... 我想使用包含字符串的变量作为函数的参数。
x <- c(1:10)
myoptions <- "trim=0, na.rm=FALSE"
现在,类似的内容
foo <- mean(x, myoptions)
相同!
foo <- mean(x, trim=0, na.rm=FALSE)
应该与“提前感谢”
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
eval
和parse
:You can use
eval
andparse
:执行您想要的操作的更自然的方法是使用
do.call
。例如,如果由于某种原因您确实想使用
myoptions
字符串,则始终可以使用strsplit
将其强制转换为列表形式。例如,A more natural way to do what you want is to use
do.call
. For example,If for some reason you really want to use a
myoptions
string, you could always usestrsplit
to coarce it into a list form. For example,这是第三个答案,它都使用
parse
、alist
和do.call
。我提出这个新答案的动机是在参数从客户端作为字符以交互方式传递的情况下。那么我想,没有什么好办法可以不使用parse
。建议使用strsplit
解决方案,无法理解逗号,
是否表示下一个参数或参数内的下一个参数的上下文。strsplit
无法理解上下文,因为strsplit
不是解析器。这里参数可以作为
"a=c(2,4), b=3,5"
或list("c(a=(2,4)","b= 3","5")
Here's a third answer that both uses
parse
,alist
anddo.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 usingparse
. Suggested solution withstrsplit
, cannot understand the context whether a comma,
means next argument or next argument within an argument.strsplit
does not understand context asstrsplit
is not a parser.here arguments can be passed as
"a=c(2,4), b=3,5"
orlist("c(a=(2,4)","b=3","5")
使用所有的
do.call
,eval
和parse
(结合kohske和csgillespie的答案,以及WoDoSc 对“将逗号分隔的字符串作为 a 传递”的回答list'):此解决方案在更复杂的情况下可以具有相当的弹性,如下所示。
结果是:
...并且...
结果
Using all of
do.call
,eval
andparse
(combining kohske's and csgillespie's answers, and also WoDoSc's answer to 'Pass a comma separated string as a list'):This solution can be quite resilient in a more complex case, such as shown below.
results in:
...and...
results in