我有一个随机数字矢量:
a <- rnorm(10)
我想做以下事情:
等等,直到序列结束。
例如:
如果数字为1 4 5 3 1
我首先比较1和4,因为4更大,我继续 然后我比较4和5,因为5更大,我继续 然后我比较5和3,因为3很小我停止并打印5的位置,这是序列中最高元素的位置。
答案 0 :(得分:3)
也许使用Position
:
a <- c(1,4,5,3,1)
#position will find the first element in the diff(a) that is negative
#and will output its position. The vector diff is n-1 the length
#of a so this will result in printing the position required by the OP
Position(function(x) x < 0 , diff(a))
[1] 3
答案 1 :(得分:2)
示例:
set.seed(1118)
s <- sample(10)
s
[1] 5 4 10 8 9 3 6 7 1 2
通过上面的示例,我们可以看看使用diff
来隔离序列中的积极变化:
which(diff(s) < 0)
[1] 1 3 5 8
修改强>
对于第一个值,只有子集中序列中较高数字的向量:
which(diff(s) < 0)[1]
[1] 1
您的原始示例:
s <- c(1, 4, 5, 3, 1)
which(diff(s) < 0)[1]
[1] 3
答案 2 :(得分:1)
| snapshot | val | val | grp |
|----------|--------|--------|-----|
| 201201 | (null) | (null) | 0 |
| 201202 | (null) | (null) | 0 |
| 201203 | 10 | 10 | 1 |
| 201204 | (null) | 10 | 1 |
| 201405 | (null) | 10 | 1 |
| 201406 | 20 | 20 | 2 |
| 201407 | 30 | 30 | 3 |
| 201408 | (null) | 30 | 3 |
| 201409 | (null) | 30 | 3 |
| 201410 | (null) | 30 | 3 |
| 201411 | (null) | 30 | 3 |
| 201412 | 40 | 40 | 4 |
| 201501 | (null) | 40 | 4 |
应该做的伎俩
min(which(diff(x) < 0))