Megatron Megatron - 4 days ago 5
R Question

Default matrix number of columns and rows in R

In R, I can create a matrix with

matrix()
, which has the function definition:

function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
{ ... }


This suggests that the default value for number of rows (
nrow
) and columns (
ncol
) are 1.

So why does the following break? Why does specifying the same default values of
1
result in a different matrix?

> matrix(1:9)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9

> matrix(1:9, ncol=1, nrow=1)
[,1]
[1,] 1

Answer

The user-facing base::matrix calls an internal function:

matrix
# function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) 
# {
#     if (is.object(data) || !is.atomic(data)) 
#         data <- as.vector(data)
#     .Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow), 
#         missing(ncol)))
# }
# <bytecode: 0x000000000b802e88>
# <environment: namespace:base>

In particular, note that the last two arguments passed to the internal function are flags indicating if the row and / or column dimensions were specified: missing(nrow), missing(ncol). The fact that these parameters have default values does not preclude them from being "missing". For example,

f <- function(x = 1, y = 2) {
    cat(sprintf(
        "missing(x): %s\nmissing(y): %s\n", 
        missing(x), 
        missing(y)
    ))
}

f()
# missing(x): TRUE
# missing(y): TRUE

Since the "missing-ness" of these arguments is not affected by the fact that they have default values, that logic can be handled independently, as is done here.

Comments