[英]R: cannot fully capture all arguments using deparse and substitute when function call is 3 dots
我正在嘗試捕獲函數調用的所有參數,因此使用了deparse和replace。 在我想使用3個點作為參數擴展函數的用法之前,它一直工作良好。 原來只有第一個參數被捕獲。 該功能的簡化版本如下所示。
func_3dot <- function(...){
tmp <- deparse(substitute(...))
print(tmp)
}
對於下面的示例,應使用[1]“ mod_1”“ mod_2”。 有什么辦法可以在不改變上述功能的情況下仍然捕獲所有輸入參數? 謝謝!!
mod_1 <- lm(mpg ~ wt, data = mtcars)
mod_2 <- update(mod_1, . ~ . + hp)
> func_3dot(mod_1, mod_2)
[1] "mod_1"
使用list(...)
而不是...
,並分別解析條目。 例如,
func_3dot <- function(...){
tmp <- substitute(list(...))
sapply(tmp, deparse)[-1]
}
[-1]
從已刪除的結果中刪除對list
的調用。
您可以使用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"
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"
或使用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.