以下代码提供了示例数据:
library(TTR)
set.seed(15)
r <- rnorm(1000, 0, .01)
P_1 <- 100
P <- P_1*cumprod(1+r)
zz <- ZigZag(P, change = 5, percent = TRUE)
set.seed(15)
volume <- round(runif(1000, 50, 550), digits = 0)
data <- as.data.frame(cbind(P, zz, volume))
plot(P, type = "l")
lines(zz, col = "red")
最后我想在新列中创建累积的音量总和,当曲折线(zz)改变方向时会发生重置。我曾尝试使用s <- sign(diff(data$zz, lag = 1))
,这会显示那些转折点,但却无法使用cumsum。
答案 0 :(得分:2)
以下是使用dplyr
的解决方案:
library(dplyr)
data %>%
mutate(
zz_up = (zz - lag(zz) > 0),
zz_switch = zz_up != lag(zz_up),
zz_switch = ifelse(is.na(zz_switch), FALSE, zz_switch),
group = cumsum(zz_switch)
) %>%
group_by(group) %>%
mutate(cum_volume = cumsum(volume))
答案 1 :(得分:2)
尝试RcppRoll
:
Vectorize(require)(package = c("magrittr", "dplyr", "RcppRoll"),
char = TRUE)
data %<>%
# Create difference for ZigZag
mutate(diffZZ = c(0,diff(zz))) %>%
# Use it as a group
group_by(diffZZ) %>%
# Use RcppRoll to compute that sum
mutate(sumVolByDiff = roll_sum(x = volume, n = 2, fill = NA)) %>%
# Clean / not important
ungroup()
> head(data)
Source: local data frame [6 x 5]
P zz volume diffZZ sumVolByDiff
(dbl) (dbl) (dbl) (dbl) (dbl)
1 100.2588 100.2588 351 0.000000 NA
2 102.0947 100.5596 148 0.300785 523
3 101.7480 100.8604 533 0.300785 1077
4 102.6608 101.1612 375 0.300785 609
5 103.1618 101.4620 234 0.300785 692
6 101.8668 101.7627 544 0.300785 938