r - 查找向量中下一个更高值之前的值的数量

标签 r vector apply purrr

假设我有一个向量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)

但众所周知,这是低效且不优雅的。

我还尝试了递归函数:

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)] 子向量。

预先感谢您的建议。

最佳答案

我们可以循环遍历向量的序列(sapply),通过与当前元素(v[i ])使用 which,对第一个位置 ([1]) 进行子集化并返回索引。

sapply(seq_along(v), \(i) which(v[-(seq_len(i))] > v[i])[1])
[1]  4  1  2  1 NA  1 NA NA

\(i)R 最新版本中 lambda 表达式的紧凑选项。如果我们有较旧的 R 版本,请使用 News 4.1.0 中通知的 function(i)

R now provides a shorthand notation for creating functions, e.g. (x) x + 1 is parsed as function(x) x + 1.

sapply(seq_along(v), function(i) which(v[-(seq_len(i))] > v[i])[1])

关于r - 查找向量中下一个更高值之前的值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72219205/

相关文章:

python-3.x - 如何在每组pandas groupby对象中添加标志列

r - 将数据帧转换为 R 频率表并使其类似于 R 频率表

R组由|计算按另一列分组的不同值

c++ - 使用 partial_sum 累积 vector 值

c++ - vector和deque的区别

r - 将数据框中的每个元素除以第二个数据框中的特定元素

r - 数据框中所有列的唯一值计数

r - 计算 R 中稀疏矩阵的特征向量

Java vector 内积

r - 按行获取 x 值之间的平均列数