更改 R 中函数的默认参数

change the default arguments of a function in R

我正在跟进 。我想知道是否有办法在 library(effects) 生成的图中将参数 rug 的默认值设置为 FALSE 并将参数 multiline 的默认值设置为 TRUE 作为,例如,代码如下所示?

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

注意:以下建议是指在函数中更改默认值的一般情况。

是的,乱用默认参数是可能的。一种方法是修改函数的 formals,在本例中为

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

另一种可能性是使用 default 包,例如

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

引用包说明,

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

关于包的更多信息,您可以查看CRAN页面。

我认为如果您只是想将这两个选项添加到您引用的@MrFlick 的回答中,您可以执行以下操作:

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)