将函数应用于相同大小的连续子向量 [英] Applying function to consecutive subvectors of equal size
问题描述
我正在寻找一种很好且快速的方法来将一些对向量进行操作的任意函数(例如 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屋!