Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

length between 2 values

Tags:

r

vector

In R, what is the most efficient way to count the length between 2 values. for example, i have vector x , which are all randomly choose from 1 to 100, how can i find out the length between the first"2" and 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

like image 391
alex Avatar asked Jul 25 '26 02:07

alex


1 Answers

I am not sure I have understood exactly what you want, but here is an 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
like image 55
George Dontas Avatar answered Jul 26 '26 18:07

George Dontas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!