change the default arguments of a function in R

Viewed 416

I'm following up on this answer. I'm wondering if there is a way to set the default for argument rug to FALSE and argument multiline to TRUE in the plots generated by library(effects) as, for example, shown below in the code?

library(effects)
m <- lm(Fertility ~ Examination*Education, data = swiss)
plot(allEffects(m), rug = FALSE, multiline = TRUE)   # By default, change `rug = FALSE`
                                                     # `multiline = TRUE `
2 Answers

Note: The below suggestions refer to the general case of changing default values in a function.

Yes, messing with the default arguments is possible. One way is to modify the formals of the function, in this case that would be

formals(effects:::plot.eff)$rug <- FALSE
formals(effects:::plot.eff)$multiline <- TRUE

Another possibility is to use the default package like

default::default(effects:::plot.eff) <- list(rug = FALSE, 
                               multiline = TRUE)

To cite the package description,

A simple syntax to change the default values for function arguments, whether they are in packages or defined locally.

For more information on the package, you can look up the CRAN page.

I think if you're just trying to add those two options to @MrFlick's answer you reference, you could do the following:

plot.efflist <- function (x, selection, rows, cols, graphics = TRUE, 
                          lattice, rug = FALSE, multiline = TRUE, ...) 
{
  lattice <- if (missing(lattice)) 
    list()
  else lattice
  if (!missing(selection)) {
    if (is.character(selection)) 
      selection <- gsub(" ", "", selection)
    pp <- plot(x[[selection]], lattice = lattice, rug = rug, multiline=multiline, ...)
    pp$x.scales$tck=c(1,0)
    pp$y.scales$tck=c(1,0)
    return(pp)
  }
  effects <- gsub(":", "*", names(x))
  neffects <- length(x)
  mfrow <- mfrow(neffects)
  if (missing(rows) || missing(cols)) {
    rows <- mfrow[1]
    cols <- mfrow[2]
  }
  for (i in 1:rows) {
    for (j in 1:cols) {
      if ((i - 1) * cols + j > neffects) 
        break
      more <- !((i - 1) * cols + j == neffects)
      lattice[["array"]] <- list(row = i, col = j, 
                                 nrow = rows, ncol = cols, more = more)
      pp <- plot(x[[(i - 1) * cols + j]], lattice = lattice, rug=rug, multiline=multiline,
                 ...)
      # hack to turn off opposite side tick marks
      pp$x.scales$tck=c(1,0)
      pp$y.scales$tck=c(1,0)
      print(pp)
    }
  }
}
environment(plot.efflist) <- asNamespace("effects")

library(effects)
m <- lm(Fertility ~ ., data = swiss)
plot(allEffects(m), rug = FALSE)

enter image description here

Related