Skip to content
Prev 257973 / 398502 Next

My code is too "loopy"

Hi:

I think the embed() function is your friend here. From its help page example,
[,1] [,2] [,3]
[1,]    3    2    1
[2,]    4    3    2
[3,]    5    4    3
[4,]    6    5    4
[5,]    7    6    5
[6,]    8    7    6
[7,]    9    8    7
[8,]   10    9    8


Applying it to your test data,

# h() creates a weighted average of the observations in each row
h <- function(x) embed(x, 3) %*% c(0.5, 0.35, 0.15)
library(plyr)
ddply(mydata, "group", summarise, ma = h(myvalue))
    group     ma
1  group1  11.00
2  group1  16.75
3  group1   9.25
4  group1   3.00
5  group1   0.00
6  group1   5.00
7  group2  85.00
8  group2  30.00
9  group2 150.00
10 group2 205.00
11 group2 115.00
12 group2  30.00

Does that work for you? The rollapply() function in the zoo package
may also be applicable with a similar input function that computes a
weighted average.

HTH,
Dennis


On Mon, Apr 25, 2011 at 1:50 PM, Dimitri Liakhovitski
<dimitri.liakhovitski at gmail.com> wrote: