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
?
You can use substitute
, which is also useful for when you want to use variable names as labels.
do.call("fix",list(substitute(dfr)))
Edit for clarity
It is easier to see how this works by using the call
command:
> call("fix",dfr)
fix(list(x = c(1, 2, 3, 4, 5), y = 1:5))
> call("fix",substitute(dfr))
fix(dfr)
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 an eval
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:
> as.name("dfr")==substitute(dfr)
[1] TRUE
The first error gives you a hint. This works:
do.call(fix,list("dfr"))
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 to what
(the function). So your second try should be:
do.call(fix,list(x="dfr"))
精彩评论