更改 R 中函数的默认参数

问题描述

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

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)

引用包描述,

更改函数参数默认值的简单语法,无论它们是在包中还是在本地定义。

有关该包的更多信息,您可以查看 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]],rug=rug,...)
      # 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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...