I would like to set
byrow=TRUE
as the default behavior for the
matrix()
function in R. Is there any way to do this?
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
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.
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.
C. All the parameters of a function can be default parameters.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With