I have a dataset that has only one variable v.
I want to calculate for every new row the previous cumulative max value of v (maxprix) and the previous cumulative standard deviation (sdd).
For every row I want to test if the v is bigger than maxprix + 2.5 sdd. If it is the case, v become maxprix + sdd. And next maxprix and sdd take the modification of v into account
But case_when(), modify only the first occurence that satisfy the condition.
How can I modify all values( raw5, 8 and 10)
library(dplyr)
v<-c(1,2,3,4,50,6,7,1000,9,1200,10) data = data.frame(v) data
#after modification
data<-data%>% mutate(maxprix= ave(v, FUN=function(x) sapply(sapply(seq_along(x)-1, head, x=x), max)))%>% mutate(sdd=ave(v,FUN=function(x) sapply(sapply(seq_along(x)-1, head, x=x), sd)))%>% mutate(v= case_when(v>maxprix+(2.5 * sdd) ~ (maxprix + sdd), TRUE ~ (v)))%>% mutate(maxprix= ave(v, FUN=function(x) sapply(sapply(seq_along(x)-1, head, x=x), max)))%>% mutate(sdd= ave(v,FUN=function(x) sapply(sapply(seq_along(x)-1, head, x=x), sd)))
data