# 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)
return(sig.s)
}
```

I need somthing like this:

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

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:

```library("data.table")
set.seed(4444)
df <- data.frame(value = round(runif(10, 1 , 1000), 0),
weight = round(runif(10, 0.1, 0.99), 2))
setDT(df)

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.