“sliding window”/partition over elements

2019-03-01 11:10发布

问题:

Given the sequence 1 2 3 4, I would like to generate a matrix of pairs

1 2
2 3
3 4

to use as indexes for another matrix. What would be the fastest way to achieve this?

回答1:

You could use embed(), reversing the columns on the output.

embed(1:4, 2)[, 2:1]
#      [,1] [,2]
# [1,]    1    2
# [2,]    2    3
# [3,]    3    4


标签: r vector