2010-04-17 73 views
3

在R中,计算2个值之间长度的最有效方法是什么?例如,我有矢量x,它们都是从1到100中随机选择的,我如何找出第一个“2”和第一个“40”之间的长度, x =(1,2,3,4, 5,6,7,40,1,2,3,21,4,1,23,4,433,4,12,34,3,5,36,3,45,12,31 ,3,4,23,41,23,5,53,45,3,7,6,36) 为这个载体,答案应该是5和62个值之间的长度

回答

5

我不知道我已经明白了什么你想,但这里是一种方法

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

arr.ind = TRUE这是什么意思? – alex 2010-04-17 06:25:18

+0

这里不需要,我会纠正它。阅读http://finzi.psych.upenn.edu/R/library/base/html/which.html – 2010-04-17 06:50:22