Search code examples
rmatrixtransformmultiple-columnsrows

Vector to a matrix where the next row starts 1 observation


Suppose I have a data set with 40 observations

y <- rnorm(40,10,10)

Now I would like to transform this vector into a matrix with 4 observations in each row. On top of that, I would like the row to start with value y[i] and add one each iteration upuntil the 40th observation. So for example:

r1 = y[1] y[2] y[3] y[4]
r2 = y[2] y[3] y[4] y[5]
r3 = y[3] y[4] y[5] y[6]
.
.
r40 = y[39] y[38] y[37] y[36]

Does anyone know how to do this?


Solution

  • You can use matrix like:

    y <- 1:40
    matrix(y, 41, 4)[1:37,]
    #     [,1] [,2] [,3] [,4]
    # [1,]    1    2    3    4
    # [2,]    2    3    4    5
    # [3,]    3    4    5    6
    #...
    #[35,]   35   36   37   38
    #[36,]   36   37   38   39
    #[37,]   37   38   39   40
    

    Or using seq in mapply and fill the index matrix with the values of y.

    i <- 1:37
    M <- t(mapply(seq, i, i+3))
    M
    #      [,1] [,2] [,3] [,4]
    # [1,]    1    2    3    4
    # [2,]    2    3    4    5
    # [3,]    3    4    5    6
    #...
    #[35,]   35   36   37   38
    #[36,]   36   37   38   39
    #[37,]   37   38   39   40
    
    M[] <- y[M]