【问题标题】:Set default values for function parameters in R在 R 中设置函数参数的默认值
【发布时间】:2015-01-17 01:39:23
【问题描述】:

我想设置

byrow=TRUE

作为默认行为

matrix()

R 中的函数。有没有办法做到这一点?

【问题讨论】:

  • 或者,你也可以mmatrix <- function(...,byrow=T) matrix(...,byrow=byrow)

标签: r defaults


【解决方案1】:

您可以使用formals<-替换功能。

但首先,最好将matrix() 复制到一个新函数中,这样我们就不会弄乱使用它的任何其他函数,也不会因为更改形式参数而导致 R 出现任何混乱。这里我就叫它myMatrix()

myMatrix <- matrix
formals(myMatrix)$byrow <- TRUE
## safety precaution - remove base from myMatrix() and set to global
environment(myMatrix) <- globalenv()

现在myMatrix()matrix() 相同,除了byrow 参数(当然还有环境)。

> myMatrix
function (data = NA, nrow = 1, ncol = 1, byrow = TRUE, dimnames = NULL) 
{
    if (is.object(data) || !is.atomic(data)) 
        data <- as.vector(data)
    .Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow), 
        missing(ncol)))
}

这是一个测试运行,显示带有默认参数的matrix(),然后是带有默认参数的myMatrix()

matrix(1:6, 2)
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6
myMatrix(1:6, 2)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 2010-10-28
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    相关资源
    最近更新 更多