apply, mapply? I`m trying to calculate weighted moving average in R

I have two columns/vectors and I´d like to get the weighted average. I found this but I cannot change lambda to a colum/vector.

wma.func = function(rets, lambda) {
  sig.p = rets[1]
  sig.s = vapply(rets, function(r) sig.p <<- sig.p*lambda + (r)*(1 - lambda), 0)

I need somthing like this:

lwma.func = function(rets, wt) {
  sig.p = rets[1]
  sig.w = wt[1] ????
  sig.s = vapply(rets, function(r) sig.p <<- sig.p*sig.w + (r)*(1 - sig.w), 0)

So that in each row it sums the last value times the weight of this specific row plus the actual value times one minus the specific row.

As well I don´t really understand how

function(r) sig.p <<- sig.p*sig.w + (r)*(1 - sig.w)

This function works? What does <<- means? Thank you for your help.


Here's a data.table way to do that:

df <- data.frame(value = round(runif(10, 1 , 1000), 0),
                 weight = round(runif(10, 0.1, 0.99), 2))

df[, new := shift(x = value, n = 1, type = "lag") * weight + value * (1 - weight)]

PS You can look up the <<- operator by entering ?`<<-`, which basically tells you that it assigns a value to the parent environment instead of just the function's immediate environment.

Need Your Help

Error when I send email SparkPost


First the "email send" works fine but now It doesn't work anymore and when I print the error this is the text:

When developing a database, is it important to keep in mind a future application?

database database-design relational-database

I am in the process of designing a database for the first time outside of the classroom in order to make a future java application work with complete desired functionality. As I am trying to design