Change default arguments of an R function at runti

2019-04-06 10:24发布

Is it possible to change the default values of formal parameters in an R function at runtime?

Let's assume, we have the function

f <- function(x=1) { 
    ...
}

can I somehow change the default value of x from 1 to, say, 2?


Thanks in advance,
Sven

标签: r reflection
3条回答
贪生不怕死
2楼-- · 2019-04-06 10:38

An alternative (shown in a different SO post) is to use the formals function, e.g.:

formals(f) <- 2

查看更多
爷的心禁止访问
3楼-- · 2019-04-06 10:41

As the Defaults package is no longer available from CRAN, you can use default.

As an example:

x <- list(a = 1, b = 2, c = 3)
default::default(unlist) <- list(use.names = FALSE)
unlist(x)
#> [1] 1 2 3

unlist <- default::reset_default(unlist)
unlist(x)
#> a b c 
#> 1 2 3

Created on 2019-03-22 by the reprex package (v0.2.0.9000).

查看更多
你好瞎i
4楼-- · 2019-04-06 10:45

Yes, the Defaults package allows you to do this.

查看更多
登录 后发表回答