When I convert a vector to a matrix that has too few elements to fill the matrix, then the elements of the vector are recycled. Is there any way to turn recycling off or otherwise replace the recycled elements with NA?
This is the default behavior:
> matrix(c(1,2,3,4,5,6,7,8,9,10,11),ncol=2,byrow=TRUE)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
[6,] 11 1
Warning message:
In matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), ncol = 2, byrow = TRUE) :
data length [11] is not a sub-multiple or multiple of the number of rows [6]
I would like the resulting matrix to be
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
[6,] 11 NA
You can't turn recycling off, but you can do some manipulations to the vector before you form the matrix. We can extend the length of the vector based on what the dimensions of the matrix will be. The length<-
replacement function will pad the vector with NA
up to the desired length.
x <- 1:11
length(x) <- prod(dim(matrix(x, ncol = 2)))
## you will get a warning here unless suppressWarnings() is used
matrix(x, ncol = 2, byrow = TRUE)
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
# [3,] 5 6
# [4,] 7 8
# [5,] 9 10
# [6,] 11 NA
This will create a matrix with nr
rows containing x
with NAs at the end without any warnings.
# inputs
nr <- 2
x <- 1:11
nc <- ceiling(length(x) / nr)
and then any of the following:
t(replace(matrix(NA, nc, nr), seq_along(x), x))
matrix(`length<-`(x, nr * nc), nr, byrow = TRUE)
matrix(c(x, rep(NA, nr * nc - length(x))), nr, byrow = TRUE)
matrix(replace(rep(NA, nr * nc), seq_along(x), x), nr, byrow = TRUE)
To fill the matrix by column use this in place of the first alternative and omit byrow=TRUE
for the remaining alternatives.
replace(matrix(NA, nr, nc), seq_along(x), x)