计算较大向量的子向量的最大值 [英] Calculating the maximum of sub-vectors of a larger vector

查看:33
本文介绍了计算较大向量的子向量的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在较长向量的一部分中找到最大的元素.我还想对这个较大向量的多个部分"执行此计算.下面的代码产生了我正在寻找的结果,但使用循环似乎效率低下.建议?

I would like to find the largest element in a portion of a longer vector. I would also like to perform this calculation for multiple 'pieces' of this larger vector. The following code produces the result I am looking for, but it seems inefficient to use a loop. Suggestions?

注意:我并不特别局限于使用向量数据结构来解决这个问题.

Note: I am not specifically limited to using the vector data structure to solve this problem.

test.vec = as.vector(c(1,2,4,3,2,3,4,5,4,3,4,5))
output.vec = vector(mode = 'numeric', length = length(test.vec))
for(i in 1:length(test.vec)){
output.vec[i] = max(test.vec[1:i])
}
output.vec = 1, 2, 4, 4, 4, 4, 4, 5, 5 ,5 ,5 ,5  #Result of the loop

推荐答案

这应该可以解决问题

cummax(test.vec)

除了 sum、min、max、prod(内置更高效的例程)之外,一般的策略可能是

Besides sum, min, max, prod, for which a more efficient routine is built-in, the general strategy might be

Reduce(max, test.vec, accumulate = TRUE)

这篇关于计算较大向量的子向量的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆