Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Vector to Matrix without Recycling

Tags:

r

vector

matrix

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
like image 474
David Dickson Avatar asked Apr 30 '15 02:04

David Dickson


2 Answers

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
like image 103
Rich Scriven Avatar answered Nov 08 '22 14:11

Rich Scriven


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)
like image 3
G. Grothendieck Avatar answered Nov 08 '22 15:11

G. Grothendieck