Try this:
df1$SMA <- ave(df1$col4, df1$col1, FUN = function(x) c(NA, (head(x,
-1) + tail(x, -1))/2))
It would also be possible to convert it from long form to wide form
using reshape (or read.zoo in the devel version of zoo), convert that
to a zoo series and the use rollapply in the zoo package.
Dear all,
If I have the following data frame:
> set.seed(21)
> df1 <- data.frame(col1=c(rep('a',5), rep('b',5), rep('c',5)),
> col4=rnorm(1:15))
col1 col4
1 a 0.793013171
2 a 0.522251264
3 a 1.74641
4 a -1.271336123
5 a 2.197389533
6 b 0.433130777
7
Dear all,
If I have the following data frame:
> set.seed(21)
> df1 <- data.frame(col1=c(rep('a',5), rep('b',5), rep('c',5)),
> col4=rnorm(1:15))
col1 col4
1 a 0.793013171
2 a 0.522251264
3 a 1.74641
4 a -1.271336123
5 a 2.197389533
6 b 0.433130777
7
3 matches
Mail list logo