I have large data sets that I need to produce moving averages for.
I use df$new_value1=replace(df$value, df$value<2.0,0)
to pull what I need (i.e. values >=2.0).
I then use df$new_value2=round((df$new_value1)*50,1)
Once I have the date the way I need I compute the SMA using:
df=df%>%
group_by(Name) %>%
mutate(SMA1 = round(TTR::SMA(new_value2,50),1)) %>%
mutate(SMA2 = round(TTR::SMA(new_value2,100),1)) %>%
mutate(SMA3 = round(TTR::SMA(new_value2,150),1)) %>%
mutate(SMA4 = round(TTR::SMA(new_value2,200),1)) %>%
mutate(SMA5 = round(TTR::SMA(new_value2,250),1))`
While this works for the most part and it will create the SMA as I need, I will get outputs like this:
Name new_value2 SMA5(Current) SMA5(What it should be)
A 2.2
A 2.3
A 2.5
A 3.0
A 2.7 2.54 2.54
A 2.1 2.52 2.53
A 0 2.52 2.06
A 0 2.52 1.56
A 0 2.52 0.96
A 0 2.52 0.42
A 0 0.00 0.00
My problem is that it holds on to the last number (almost to look like it doesn't recognize the zeros) rather than averaging down with the zeros. I'd like the data to look like the far right column but it looks like the 3rd column right now. I'm not sure what the issue is.