Khaynes
Khaynes

Reputation: 1986

Change default argument(s) of S3 Methods in R

Is it possible to change default argument(s) of S3 Methods in R?

It's easy enough to change arguments using formals ...

# return default arguments of table
> args(table)
function (..., exclude = if (useNA == "no") c(NA, NaN), useNA = c("no", 
"ifany", "always"), dnn = list.names(...), deparse.level = 1) 

# Update an argument
> formals(table)$useNA <- "always"

# Check change
> args(table)
function (..., exclude = if (useNA == "no") c(NA, NaN), useNA = "always", 
dnn = list.names(...), deparse.level = 1) 

But not S3 methods ...

# View default argument of S3 method
> formals(utils:::str.default)$list.len
[1] 99

# Attempt to change
> formals(utils:::str.default)$list.len <- 99
Error in formals(utils:::str.default)$list.len <- 99 : 
object 'utils' not found

Upvotes: 2

Views: 324

Answers (1)

gfgm
gfgm

Reputation: 3647

At @nicola's generous prompting here is an answer-version of the comments:

You can edit S3 methods and other non-exported functions using assignInNamespace(). This lets you replace a function in a given namespace with a new user-defined function (fixInNamespace() will open the target function in an editor to let you make a change).

# Take a look at what we are going to change
formals(utils:::str.default)$list.len
#> [1] 99    

# extract the whole function from utils namespace
f_to_edit <- utils:::str.default
# make the necessary alterations
formals(f_to_edit)$list.len<-900
# Now we substitute our new improved version of str.default inside
# the utils namespace
assignInNamespace("str.default", f_to_edit, ns = "utils")

# and check the result
formals(utils:::str.default)$list.len
#> [1] 900

If you restart your R session you'll recover the defaults (or you can put them back manually in the current session).

Upvotes: 1

Related Questions