'Pass missing argument to function using do.call
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]
Solution 1:[1]
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.
Solution 2:[2]
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 rlangs missing_arg():
do.call(`[`, list(x, rlang::missing_arg() , 1))
First answer: not good -> see comments moodymudskipper:
We could use rlangs 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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
