-4

I have to calculate Simple Moving Averages on some data with this formula in R:

formula

Does anybody know how to do that?

user888
  • 7
  • 5

1 Answers1

1

Are you looking for something like that?

Func <- function(xt){
  St <- 1/10*sum(sapply(0:9, function(z) xt-z))
  return(St)
}

And the output for two example of Xt:

> Func(10)
5.5
> Func(15)
10.5
dc37
  • 15,840
  • 4
  • 15
  • 32
  • Your function doesn't actually return the value; it only prints it to the console. Presumably the OP will want to actually get the result – camille Jan 08 '20 at 05:36
  • @Camille, sorry, I'm not sure to understand your comments.. should I add `St <- Func(xt)` ? – dc37 Jan 08 '20 at 05:49
  • If you want a function to return a value, you need to end it with the value it should return, or explicitly call `return(St)` somewhere in the function definition. Right now, if you called `x <- Func(10)`, x would be null, and the only information you would be getting from the function would be printed to the console, which isn't often very useful – camille Jan 08 '20 at 16:44
  • @camille, thank you for your help. I was not aware of this. I'm editing my function to provide a `return`. – dc37 Jan 08 '20 at 17:20