Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default values for function parameters in R

Tags:

r

defaults

I would like to set

byrow=TRUE

as the default behavior for the

matrix()

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

like image 339
WestCoastProjects Avatar asked Jan 17 '15 01:01

WestCoastProjects


People also ask

Can you assign the default values to a function parameters?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

How do you pass a parameter to default value in R?

Adding Default Value in R If the value is passed by the user, then the user-defined value is used by the function otherwise, the default value is used. Below is an implementation of function with default value. # a is divisible by b or not.

How do you give a parameter a default value?

The default value of the message paramater in the say() function is 'Hi' . In JavaScript, default function parameters allow you to initialize named parameters with default values if no values or undefined are passed into the function.

Can all the parameters of a function can be default parameters?

C. All the parameters of a function can be default parameters.


1 Answers

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
like image 114
Rich Scriven Avatar answered Oct 11 '22 02:10

Rich Scriven