Length between two values

In R, the most efficient way to count the length between two values. for example, I have a vector x that everyone randomly selects from 1 to 100, how can I find out the length between the first "2" and the first "40", x = (1,2, 3,4,5,6,7 , 40,1,2, 3,21,4,1,23,4 , 43, 23,4,12,3,43,5,36,3,45,12,31,3,4,23,41 , 23,5,53,45,3,7,6,36) for this vector the answer should be 5 and 6

+3
source share
1 answer

I'm not sure I understood exactly what you want, but here is the approach

x<-c(1,2,3,4,5,6,7,40,1,2,3,21,4,1,23,4,43,23,4,12,3,43,5,36,3,45,12,31,3,4,23,41,23,5,53,45,3,7,6,36)

first2 <- which(x==2)[1]
first40 <- which(x>=40)[1]

first40 - first2 - 1
> 5

sec2 <- which(x==2)[2]
sec40 <- which(x>=40)[2]

sec40 - sec2 - 1
> 6
+5
source

Source: https://habr.com/ru/post/1741554/


All Articles