0
votes

Suppose I have a zoo object:

> df <- data.frame(col1=c(1,2,3,4), col2=c("a","b","c","d"))
> v <- zoo(df, order.by = df$col2)
> v
col1 col2
a 1    a   
b 2    b   
c 3    c   
d 4    d   

I can calculate the mean as:

> rollapply(v, 2, by.column = F, function(x) { mean(as.numeric(x[,"col1"])) })
 a   b   c 
1.5 2.5 3.5 

How do I rollapply mean in DESCENDING order? (please no solutions where you just reverse the results AFTER applying the regular rollapply)

I would like my output to look like:

 d   c   b 
3.5 2.5 1.5 
2

2 Answers

2
votes

The oo in zoo stands for ordered observations and such objects are always ordered by the index; however, what is shown in the question is not ordered by the index so it cannot be a valid zoo object.

Also, the line starting v <- in the question is not likely what is wanted since it seems to ask for a mix of numeric and character data. Fixing that line and creating a data frame with the order shown we have:

library(zoo)

v <- read.zoo(df, index = "col2", FUN = c)
r <- rollapplyr(v, 2, mean)
fortify.zoo(r)[length(r):1, ]

giving:

  Index   r
3     d 3.5
2     c 2.5
1     b 1.5
0
votes

Per G. Grothendieck:

rollapply(rev.zoo(v), 2, by.column = F, function(x) { mean(as.numeric(x[,"col1"])) })