我的数据集如下所示
xx = c(1:5, 1:9, 1:7)
# [1] 1 2 3 4 5 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7
我想知道索引1和序列重新开始之前的最大值。例如:
[1] 1, 1
[2] 5, 5
[3] 6, 1
[4] 14, 9
[5] 15, 1
[6] 21, 7
依旧.....
答案 0 :(得分:1)
选项是(假设vector
仅包含序列元素)
v1 <- which(xx == 1)
v2 <- c(rbind(v1, c(v1[-1]-1, length(xx))))
cbind(ind = v2, value = xx[v2])
# ind value
#[1,] 1 1
#[2,] 5 5
#[3,] 6 1
#[4,] 14 9
#[5,] 15 1
#[6,] 21 7
或另一种选择是对&#39; xx&#39;的元素序列进行split
。并获取每个list
ind <- unlist(lapply(split(seq_along(xx), cumsum(xx==1)), function(x) x[c(1, length(x))]))
cbind(ind, value = xx[ind])
答案 1 :(得分:0)
这可以通过有点丑陋(但有效!)lapply
:
a<-lapply(1:length(xx),function(x) {
if(x==length(xx)){c(x,xx[x])}else{
if(xx[x] == 1){c(x,1)}else{
if(xx[x]>xx[x+1]){c(x,xx[x])}
}
}
})
matrix(unlist(a),ncol = 2,byrow = T)