rdefaults

Set default values for function parameters in R


I would like to set

byrow=TRUE

as the default behavior for the

matrix()

function in R. Is there any way to do this?


Solution

  • You can use the formals<- replacement function.

    But first it's a good idea to copy matrix() to a new function so we don't mess up any other functions that use it, or cause R any confusion that might result from changing the formal arguments. Here I'll call it myMatrix()

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

    Now myMatrix() is identical to matrix() except for the byrow argument (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)))
    }
    

    And here's a test run showing matrix() with default arguments and then myMatrix() with its default arguments.

    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