开发者

length between 2 values

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,开发者_如何学JAVA4,23,41,23,5,53,45,3,7,6,36) for this vector, the answer should be 5 and 6


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜