0

I have a data frame given which a time series in column "value X".
I want to calculate single and exponential moving averages on this column (SMA and EMA).

Since you can change the parameter "n" as window size in SMA/EMA calculation I want to change the parameter in a loop starting from 5 to 150 in steps of 5. And then write the result into a data frame. So the data frame should look like.

SMA_5 | SMA_10 | SMA_15 .... EMA_5 | EMA_10 | EMA_15 ...

Ideally the column names are also created in this loop.

user438383
  • 5,716
  • 8
  • 28
  • 43
Aircan
  • 1
  • 5
    Please, share an extract of your data (anonymized) and a chunk of your code: https://stackoverflow.com/help/how-to-ask – Scipione Sarlo Dec 27 '17 at 09:15
  • As I already explained, I also tried rbind etc. but in R base this is the code I tried to loop: code k <- 5 b <- 1 repeat{ test_sma[,b] <- SMA(TestData[c('TestData$value X')], n = k) k <- k + 5 b <- b + 1 if(k > 150){break} } Writing into data frame is a mess right now. I have 5 or 6 different tries shall I post them all? – Aircan Dec 27 '17 at 10:07
  • Please do not write code in comments. Use *edit* link above. Since you are author, you can edit your own post. And please **show** and not **tell** us what you are trying to do and desired result. – Parfait Dec 27 '17 at 16:27

1 Answers1

0

As far as I know, the loops are seen as a non-optimal solution in R and should be avoided if possible. It seems to me that in-built R functions sapply and colnames may provide quite a simple solution for your problem:

library("TTR")
# example of data
test <- data.frame(moments = 101:600, values = 1:500)
seq_of_windows_size <- seq(from = 5, to = 150, by = 5)
col_names_of_sma <- paste("SMA", seq_of_windows_size, sep = "_")
SMA_columns <- sapply(FUN = function(i) SMA(x = test$values, n = i),
    X = seq_of_windows_size)
colnames(SMA_columns) <- col_names_of_sma

Then you'll have just to add the SMA_columns to your original dataframe. The steps for EMA may be much the same. Hope, it helps :)

Ekatef
  • 1,061
  • 1
  • 9
  • 12