您可以通过 do.call 使用修复吗?
我有一些代码,通过 do.call
调用 fix
比直接调用更方便。任何旧的数据框都适用于此示例:
dfr <- data.frame(x = 1:5, y = letters[1:5])
明显的第一次尝试是
do.call("fix", list(dfr))
不幸的是,这失败了
Error in fix(list(x = 1:5, y = 1:5)) : 'fix' requires a name
所以,我们给它一个名称:
do.call("fix", list(dfr = dfr))
这次失败了
Error in is.name(subx) : 'subx' is missing
郑重声明,edit
也不起作用。
dfr <- do.call("edit", list(dfr = dfr))
请问有人能想出一个合理的解决方法吗?
编辑:经过反思,我忘记了 fix
总是将其答案转储到全局环境中,这对于测试示例来说很好,但对于与函数一起使用不太好。 Joshua 的出色解决方法并没有扩展到与 edit
一起使用。
对于奖励积分,如何通过 do.call
调用 edit
?
I have some code where it is more convenient to call fix
via do.call
, rather than directly. Any old data frame will work for this example:
dfr <- data.frame(x = 1:5, y = letters[1:5])
The obvious first attempt is
do.call("fix", list(dfr))
Unfortunately, this fails with
Error in fix(list(x = 1:5, y = 1:5)) : 'fix' requires a name
So, we give it a name:
do.call("fix", list(dfr = dfr))
This time it fails with
Error in is.name(subx) : 'subx' is missing
For the record, edit
doesn't work either.
dfr <- do.call("edit", list(dfr = dfr))
Can anyone think of a sensible workaround, please?
EDIT: Upon reflection, I'd forgotten that fix
always dumps its answer into the global environment, which is fine for test examples, but not so good for use with functions. Joshua's excellent workaround doesn't extend to use with edit
.
For bonus points, how do you call edit
via do.call
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
substitute
,当您想要使用变量名称作为标签时,这也很有用。为清楚起见进行编辑
使用
call
命令可以更轻松地了解其工作原理:因此,当您使用
substitute
时,正在创建的命令使用符号的名称而不是评估的符号。如果您在这些表达式周围使用eval
,您会发现第一个示例给出了您遇到的相同错误,而第二个示例则按预期工作。阅读哈德利的链接后,正在评估的内容变得更加清晰:
You can use
substitute
, which is also useful for when you want to use variable names as labels.Edit for clarity
It is easier to see how this works by using the
call
command:Thus when you use
substitute
the command that is being created uses the name of the symbol rather than the evaluated symbol. If you wrap aneval
around these expressions you see that the first example gives the same error you encountered, and the second example works as expected.After reading hadley's link it becomes clearer what is being evaluated:
第一个错误给了你一个提示。这是有效的:
即使您使用
dfr="dfr"
,您在第二次尝试时仍然会遇到相同的错误,因为命名列表需要what
的参数名称(功能)。所以你的第二次尝试应该是:The first error gives you a hint. This works:
You would still get the same error on your second try even if you used
dfr="dfr"
because the named list needs names of the arguments towhat
(the function). So your second try should be: