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

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

问题描述

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

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天全站免登陆