Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default arguments of an R function at runtime

Tags:

r

reflection

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

like image 271
Sven Hager Avatar asked Apr 18 '12 15:04

Sven Hager


2 Answers

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).

like image 139
Alain Danet Avatar answered Oct 18 '22 02:10

Alain Danet


UPDATE: 2020-12-13

This method is no longer available

Yes, the Defaults package allows you to do this.

like image 27
Joshua Ulrich Avatar answered Oct 18 '22 01:10

Joshua Ulrich