Here is a method using outer
.
c(outer(5:7, seq(0L, 95L, 6L), "+"))
[1] 5 6 7 11 12 13 17 18 19 23 24 25 29 30 31 35 36 37 41 42 43 47 48 49 53
[26] 54 55 59 60 61 65 66 67 71 72 73 77 78 79 83 84 85 89 90 91 95 96 97
To generalize this, you could do
idx <- c(outer(seq(i, i + n), seq(0L, ncol(M) - i, 2 * n), "+"))
The idea is to construct the initial set of columns (5:7
or seq(i, i + n)
), calculate the starting points for every subsequent set (seq(0L, 95L, 6L)
or seq(0L, ncol(M) - i, 2 * n)
) then use outer
to calculate the sum of every combination of these two vectors.
you can subset the matrix using [
like M[, idx]
.