Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R iterate over consecutive pairs in a list

Tags:

list

r

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?

like image 830
Max Beikirch Avatar asked Dec 03 '22 09:12

Max Beikirch


1 Answers

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)
like image 113
akrun Avatar answered Dec 22 '22 01:12

akrun