将函数应用于大小相等的连续子向量 [英] Applying function to consecutive subvectors of equal size

查看:60
本文介绍了将函数应用于大小相等的连续子向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种很好的,快速的方法,将对向量(例如sum)连续运行的任意函数应用到连续K个元素的子向量上. 这是一个简单的示例,应该非常清楚地说明我想要的内容:

I am looking for a nice and fast way of applying some arbitrary function which operates on vectors, such as sum, consecutively to a subvector of consecutive K elements. Here is one simple example, which should illustrate very clearly what I want:

v <- c(1, 2, 3, 4, 5, 6, 7, 8)
v2 <- myapply(v, sum, group_size=3) # v2 should be equal to c(6, 15, 15)

该函数应尝试处理给定向量的group_size个元素组,并将函数应用于每个组(将其作为另一个向量进行处理).在此示例中,向量v2的获取方式如下:(1 + 2 + 3)= 6,(4 + 5 + 6)= 15,(7 + 8)=15.在这种情况下,K不精确地除以N,因此最后一组的大小小于K.

The function should try to process groups of group_size elements of a given vector and apply a function to each group (treating it as another vector). In this example, the vector v2 is obtained as follows: (1 + 2 + 3) = 6, (4 + 5 + 6) = 15, (7 + 8) = 15. In this case, the K did not divide N exactly, so the last group was of size less then K.

如果有更好/更快的解决方案,仅当N为K的倍数时才有效,我也将不胜感激.

If there is a nicer/faster solution which only works if N is a multiple of K, I would also appreciate it.

推荐答案

尝试一下:

library(zoo)
rollapply(v, 3, by = 3, sum, partial = TRUE, align = "left")
## [1]  6 15 15

apply(matrix(c(v, rep(NA, 3 - length(v) %% 3)), 3), 2, sum, na.rm = TRUE)
## [1]  6 15 15

此外,在sum的情况下,最后一个可以缩短为

Also, in the case of sum the last one could be shortened to

colSums(matrix(c(v, rep(0, 3 - length(v) %% 3)), 3))

这篇关于将函数应用于大小相等的连续子向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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