0

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.

jg23
  • 3
  • 3
  • I can't seem to replicate your problem as `round(SMA(c(2.2,2.3,2.5,3.0,2.7,2.1,0,0,0,0,0), 5),1)` gives your desired output. – Evan Friedland Apr 20 '19 at 18:05
  • maybe so, but I'm wondering if it is possibly due to the underlying formulas I'm using to get there. `df$new_value1=replace(df$value, df$value<2.0,0)` I'm wondering if the replaced "0" if it is <2.0 is not being recognized as a number, but rather as text? – jg23 Apr 21 '19 at 20:22
  • If you can give me something reproducible then I might be able to help but as of what’s above I have no way of knowing sorry – Evan Friedland Apr 21 '19 at 20:57
  • Thanks for the responses and sorry for the late response. Would I be able to send an email to you with a data / code sample? Or is there a way that I can do that through here? – jg23 May 09 '19 at 11:19
  • The best way is to please check out https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and then to edit your question – Evan Friedland May 09 '19 at 11:24

0 Answers0