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
+5
A:
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
gd047
2010-04-17 06:11:07
arr.ind = TRUE what does this mean???
alex
2010-04-17 06:25:18
Not needed here, I ll correct it. Read this http://finzi.psych.upenn.edu/R/library/base/html/which.html
gd047
2010-04-17 06:50:22