Set default values ​​for function parameters in R

I would like to set

byrow=TRUE

as default behavior for

matrix()

in R. Is there a way to do this?

+4
source share
1 answer

You can use the replace function formals<-.

But first, it is recommended to copy it matrix()into a new function, so that we do not spoil any other functions that use it, or cause R any confusion that may arise as a result of changing formal arguments. Here i will call himmyMatrix()

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

Now myMatrix()identical matrix()except for the argument byrow(and the environment, of course).

> 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
+8

All Articles