[英]R: cannot fully capture all arguments using deparse and substitute when function call is 3 dots
I am trying to capture all arguments of a function call so deparse and substitute are used. 我正在尝试捕获函数调用的所有参数,因此使用了deparse和replace。 It has worked well until I want to extend the usage of the function using 3 dots as arguments; 在我想使用3个点作为参数扩展函数的用法之前,它一直工作良好。 turns out only the first argument is captured. 原来只有第一个参数被捕获。 A simplified version of the function is shown below. 该功能的简化版本如下所示。
func_3dot <- function(...){
tmp <- deparse(substitute(...))
print(tmp)
}
For the example below [1] "mod_1" "mod_2" are expected. 对于下面的示例,应使用[1]“ mod_1”“ mod_2”。 Is there any way I could still capture all input arguments without changing the above function much? 有什么办法可以在不改变上述功能的情况下仍然捕获所有输入参数? Thanks!! 谢谢!!
mod_1 <- lm(mpg ~ wt, data = mtcars)
mod_2 <- update(mod_1, . ~ . + hp)
> func_3dot(mod_1, mod_2)
[1] "mod_1"
Use list(...)
instead of just ...
, and deparse the entries separately. 使用list(...)
而不是...
,并分别解析条目。 For example, 例如,
func_3dot <- function(...){
tmp <- substitute(list(...))
sapply(tmp, deparse)[-1]
}
The [-1]
removes the call to list
from the deparsed results. [-1]
从已删除的结果中删除对list
的调用。
You can use match.call
: 您可以使用match.call
:
func_3dot <- function(...){
tmp <- vapply(as.list((match.call()[-1])), deparse, FUN.VALUE = character(1))
print(tmp)
}
func_3dot(mod_1, mod_2)
#[1] "mod_1" "mod_2"
One option with purrr
and rlang
purrr
和rlang
一种选择
library(rlang)
library(purrr)
func_3dot <- function(...){
unname(map_chr(quos(...), quo_name))
}
func_3dot(mod_1, mod_2)
#[1] "mod_1" "mod_2"
Or using base R
或使用base R
func_3dot <- function(...){
sapply(as.list(substitute(...())), deparse)
}
func_3dot(mod_1, mod_2)
#[1] "mod_1" "mod_2"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.