1
我试图清理我的代码。目前我使用不同的参数组合多次运行rollapplyr
。下面是我使用它的功能:使用不同参数多次滚动
library('assertthat')
var_sums <- function(x, sign) {
assert_that(length(x) > 0)
if (sign == "pos") {
sum(x[which(x > 0)])
} else if (sign == "neg") {
sum(x[which(x < 0)])
} else {
stop("variable sign must have value of 'pos' or 'neg'")
}
}
它发生在一个矢量-1和1之间的正数和负数的x
,总结要么只是取决于在正面的或只是消极因素值为sign
。目前,我已经做实现了它:
library('zoo')
set.seed(1)
vec <- round(runif(100, min = -1), digits = 2)
pos_4 <- rollapplyr(vec, 4, var_sums, sign = "pos", fill = NA)
neg_4 <- rollapplyr(vec, 4, var_sums, sign = "neg", fill = NA)
pos_12 <- rollapplyr(vec, 12, var_sums, sign = "pos", fill = NA)
neg_12 <- rollapplyr(vec, 12, var_sums, sign = "neg", fill = NA)
y <- data.frame(pos_4, neg_4, pos_12, neg_12)
肯定有这样做的,我只是没有看到,使用do.call
或mapply
什么的更优雅的方式。
这是一个小的变化:'g < - expand.grid(sign = c(“pos”,“neg”),width = c(4,12)); (g,rollapplyr(x,width,var_sums,sign = sign,fill = NA)); sapply(split(g,do.call(“interaction”,g)),roll) ' –