change the default arguments of a function in R

醉酒当歌 提交于 2021-02-08 07:40:28

问题


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 `

回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/65971155/change-the-default-arguments-of-a-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!