suppose I have the following vector:
v1 = c(1,2,3,4)
I need to iterate over this vector in a pairwise fashion, like (1,2), (2,3), (3,4)
. For python, there is a solution to this problem here: Iterate over all pairs of consecutive items in a list. Can a similar solution be achieved in R?
We can remove the first
and last
elements and concatenate in Map
Map(c, v1[-length(v1)], v1[-1])
#[[1]]
#[1] 1 2
#[[2]]
#[1] 2 3
#[[3]]
#[1] 3 4
Or rbind
and use asplit
asplit(rbind(v1[-length(v1)], v1[-1]), 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With