Extract series of successive vectors from matrix

Viewed 61

I have a large matrix, say for simplification:

> mat = matrix(c(1:50), ncol = 5)
> mat
      [,1] [,2] [,3] [,4] [,5]
 [1,]    1   11   21   31   41
 [2,]    2   12   22   32   42
 [3,]    3   13   23   33   43
 [4,]    4   14   24   34   44
 [5,]    5   15   25   35   45
 [6,]    6   16   26   36   46
 [7,]    7   17   27   37   47
 [8,]    8   18   28   38   48
 [9,]    9   19   29   39   49
[10,]   10   20   30   40   50

I want to extract successively all possible vertical vectors composed of 3 elements from each column, e.g. (1,2,3), (2,3,4),...,(11,12,13), (12,13,14),... and generate a 3-by-X matrix composed of all these vectors. Something that would look like this:

      [,1] [,2] [,3] 
 [1,]    1   2   3 
 [2,]    2   3   4 
 [3,]    3   4   5 
 etc.    .   .   . 
 [5,]    11   12   13 
 [6,]    12   13   14 
 [7,]    13   14   15 
 etc.    ..   ..   .. 
 [9,]    21   22   23 
[10,]    22   23   24 

I have tried using the lapply and cbind functions, as well as a more generic for loop, but it shows "incorrect number of dimensions". Thanks for your help!

2 Answers
Related