How do I pass a missing argument to a function using do.call
? The following does not work:
x <- array(1:9, c(3, 3))
do.call(`[`, list(x, , 1))
I expect this to do the same calculation as
x[,1]
CodePudding user response:
you can use quote(expr=)
x <- array(1:9, c(3, 3))
do.call(`[`, list(x, quote(expr=), 1))
#> [1] 1 2 3
identical(x[,1], do.call(`[`, list(x, quote(expr=), 1)))
#> [1] TRUE
Created on 2022-04-20 by the reprex package (v2.0.1)
do.call(`[`, alist(x,, 1))
also works.
So does do.call(`[`, list(x, TRUE, 1))
for this specific case, since subsetting rows with TRUE
keeps all of them.
CodePudding user response:
Update: Thanks to @moodymudskipper: ("is_missing()
is always TRUE
so you're just subsetting rows and keeping everything. We could do do.call([, list(x, TRUE, 1))
. This solves this specific issue (perhaps better in fact), but not the general one of dealing with missing arguments.")
I meant rlang
s missing_arg()
:
do.call(`[`, list(x, rlang::missing_arg() , 1))
First answer: not good -> see comments moodymudskipper:
We could use rlang
s is_missing()
:
See here https://rlang.r-lib.org/reference/missing_arg.html
"rlang::is_missing() simplifies these rules by never treating default arguments as missing, even in internal contexts:"
do.call(`[`, list(x, rlang::is_missing() , 1))