1
votes

I have a list of data, which I wish to turn into a matrix. I know the exact size my matrix needs to be, but the data does not completely fill it. For example, for a vector of length 95, I would like to turn this into a 25*4 matrix. Using the matrix command does not work since the number of values does not fit the matrix so I need a way to pad this out with NAs, and fill the matrix by row.

The size of matrix will be known in each scenario, but it is not consistent from one set of data to the next, so ideally, there will be a function which automatically pads the matrix with NAs if the data is not available.

Example code:

example=c(20.28671, 20.28544, 20.28416, 20.28288, 20.28161, 20.28033, 20.27906, 20.27778, 20.27651, 20.27523, 20.27396, 20.27268, 20.27141,
  20.27013, 20.26885, 20.26758, 20.26533, 20.26308, 20.26083, 20.25857, 20.25632, 20.25407, 20.25182, 20.24957, 20.24732, 20.24507,
  20.24282, 20.24057, 20.23832, 20.23606, 20.23381, 20.22787, 20.22193, 20.21598, 20.21004, 20.20410, 20.19816, 20.19221, 20.18627,
  20.18033, 20.17438, 20.16844, 20.16250, 20.15656, 20.15061, 20.14467, 20.13527, 20.12587, 20.11646, 20.10706, 20.09766, 20.08826,
  20.07886, 20.06946, 20.06005, 20.05065, 20.04125, 20.03185, 20.02245, 20.01305, 20.00364, 20.00369, 20.00374, 20.00378, 20.00383,
  20.00388, 20.00392, 20.00397, 20.00401, 20.00406, 20.00411, 20.00415, 20.00420, 20.00425, 20.00429, 20.00434, 20.01107, 20.01779,
  20.02452, 20.03125, 20.03798, 20.04470, 20.05143, 20.05816, 20.06489, 20.07161, 20.07834, 20.08507, 20.09180, 20.09853, 20.10525,
  20.11359, 20.12193, 20.13026, 20.13860)

mat=matrix(example,ncol=4,nrow=25)

Warning message:
In matrix(example, ncol = 4, nrow = 25) :
  data length [95] is not a sub-multiple or multiple of the number of rows [25]
3

3 Answers

5
votes

Whilst I'm sure this is not the best answer it does achieve what you want:

If you try to subset a vector using [ by using indicies that are beyond it's length it will pad with NA

mat = matrix(example[1:100],nrow = 25, byrow = TRUE, ncol = 4)

This feels as though it is a bit messy though. Perhaps one of the others is better R code.

4
votes

You can try this:

mat <- matrix(NA,ncol=4, nrow=25)
mat[1:length(example)] <- example
2
votes

We can use length<- to pad NAs to the desired length if there is shortage and then call the matrix.

 nC <- 4
 nR <- 25
 matrix(`length<-`(example, nC*nR), nR, nC)

The length<- option can also be used in several other cases, i.e. in a list of vectors where the length are not equal. In that case, we pad NAs if we need to convert to data.frame or matrix.