1

Here's my problem: I have a vector and I want to convert it into a matrix with fixed number of columns, but I don't want to replicate the vector to fill the matrix when it's necessary. For example: My vector has a length of 15, and I want a matrix with 4 columns.I wish to get the matrix wit 15 elements from the vector and a 0 for the last element in the matrix. How can I do this?

Edit: Sorry for not stating the question clearly and misguiding you guys with my example. In my program,I don't know the length of my vector, it depends on other parameters and this question involves with a loop, so I need a general solution that can solve many different cases, not just my example. Thanks for answering.

Lei_Xu
  • 155
  • 7
  • assuming that the vector you have is `letters[1:15]`: `matrix(c(letters[1:15],0), ncol=4)` will give you a matrix with 4 columns – Adam Quek Apr 21 '17 at 02:19
  • `x <- 1:15; m <- matrix(x, ncol = 4); m[-seq_along(x)] <- 0` maybe – alistaire Apr 21 '17 at 02:22
  • @AdamQuek Thanks for answering. Actually that example is not quite clear ( my bad for not stating the question clearly). In my program, I don't know the length of my vector, so I cannot fill the matrix explicitly. – Lei_Xu Apr 21 '17 at 02:37
  • Please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and also the code you have tried so far. Just stating "involves with a loop" is too vague. Show us what is your expected output as well. – Adam Quek Apr 21 '17 at 02:48
  • For example: I need to discretize my time to some numerical method application. Let Tmax be my time span, and h0 be my initial step size. I need two step size: coarse one and fine one, here's the code: `h_coarse=h0*M^(-L+1) h_fine=h0*M^(-L) N_fine=round(Tmax/h_fine) N_coarse=round(Tmax/h_coarse) ` Then I need to generate a Brownian Motion path, and sum finer grids up to get coarse grids. I would like to use a matrix and an 'apply' function. And that's why I ask this question. – Lei_Xu Apr 21 '17 at 03:29

2 Answers2

2

You could subset your vector to a multiple of the number of columns (so as to include all the elements). This will add necessary amount of NA to the vector. Then convert to matrix.

x = 1:15
matrix(x[1:(4 * ceiling(length(x)/4))], ncol = 4)
#     [,1] [,2] [,3] [,4]
#[1,]    1    5    9   13
#[2,]    2    6   10   14
#[3,]    3    7   11   15
#[4,]    4    8   12   NA

If you want to replace NA with 0, you can do so using is.na() in another step

d.b
  • 32,245
  • 6
  • 36
  • 77
1

We can also do this with dim<- and length<-

n <- 4
n1 <- ceiling(length(x)/n)
`dim<-`(`length<-`(x, n*n1), c(n1, n))
#     [,1] [,2] [,3] [,4]
#[1,]    1    5    9   13
#[2,]    2    6   10   14
#[3,]    3    7   11   15
#[4,]    4    8   12   NA

data

x <- 1:15
akrun
  • 874,273
  • 37
  • 540
  • 662