假设我有一个向量v=c(10,3,5,1,12,7,9,2)
.对于每个值,我想找到"下一个更高"之前的步数,即下一个高于当前值的值.
例如,第一个值是10,下一个更高的值是12,12是从10中删除的4个步骤.所以第一个元素与4相关联.接下来,我们有一个3,后面是5:只有1步,直到下一个更高的值.因此,最终结果应该是c(4,1,2,1,NA,1,NA,NA)
,只要没有"下一个更高"的值,就插入NA:12永远不会被打败,最后的2和之前的9都不会被打败.
我可以通过"for"循环来实现:
v=c(10,3,5,1,12,7,9,2)
# stop 1 step before the last
n=length(v)-1
#initialize vector
next_higher=vector()
for (i in 1:n) {
# check if the next higher exists: the vector of higher values is non-empty
if (length(which(v[(i+1):(n+1)]>v[i]))==0) {
# if not, insert NA
next_higher=c(next_higher,NA_real_)
} else {
# else, get the index and move on
next_higher=c(next_higher,which(v[(i+1):(n+1)]>v[i])[1])
}
}
# the last one is always going to be NA
next_higher=c(next_higher,NA)
但这是出了名的低效和不雅.
我还try 了一个递归函数:
find_next_higher = function (x) {
# recursive function
ifelse(length(x)==1,
# if length is 1 there's no next higher
return(NA_real_),
# else check if there is a next higher
ifelse(length(which(x[-1]>x[1]))==0,
# if it doesn't exist, return NA and concatenate, removing the first element
return(c(NA_real_,find_next_higher(x[-1]))),
# if it does, find index and concatenate, removing the first element
return(c(which(x[-1]>x[1])[1],find_next_higher(x[-1])))
)
)
}
但我有一个深层递归问题,它不适用于大向量.
最干净的方法是什么?
我考虑过apply
函数族,或purrr
库,但没有找到一种方法来处理剩余的v[(n+1):length(v)]
子向量,而不是单独处理每个值.
提前感谢您的建议.