-2

Currently, I have a data frame (A) with row.names as dates and two column values (Xval and Yval)

 Xval,Yval
"2015-01-01",5,6
"2015-01-02",7,4
"2015-01-05",-1,10
"2015-01-06",-4,3

I have two main questions:

(Question 1) I want to compute a new data frame (B) that has row.names as dates and two columns called Xmean, Ymean where values are a lagging rolling average of the past n days. So if n = 2, then the new data frame would look like

Xval,Yval
"2015-01-02",6,5
"2015-01-05",3,7
"2015-01-06",-2.5,6.5

(Question 2) I want to then take data frame (A) and data frame (b) to compute new data frame (C) where values for each date are (A) / (B). So take each data point to divide by the the previous n day rolling average.

Attempts: (1) I know that the zoo package has rollapply which I can use to create (B). However, what if there are other things I want to compute in addition to mean (like standard deviation or product?). (2) Are there any functions to do this out there or would I have to iterate through each date in (A) and then check the corresponding value (mean, sd or product) in (B) to divide? (This would be terribly inefficient).

Thanks for the help!

Frank
  • 66,179
  • 8
  • 96
  • 180
qwer
  • 223
  • 4
  • 13

1 Answers1

1

Adding Date to the header row, create zoo objects A,B,Candcbind BandC` together with the standard deviations:

Lines <- 'Date,Xval,Yval
2015-01-01,5,6
2015-01-02,7,4
2015-01-05,-1,10
2015-01-06,-4,3'

library(zoo)
A <- read.zoo(text = Lines, header = TRUE, sep = ",")
B <- rollmeanr(A, 2)
C <- A/B
cbind(mean = B, ratio = C, sd = rollapplyr(A, 2, sd))

giving:

           Xval.mean Yval.mean Xval.ratio Yval.ratio  Xval.sd  Yval.sd
2015-01-02       6.0       5.0  1.1666667  0.8000000 1.414214 1.414214
2015-01-05       3.0       7.0 -0.3333333  1.4285714 5.656854 4.242641
2015-01-06      -2.5       6.5  1.6000000  0.4615385 2.121320 4.949747
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • If I wanted to take a weighed sd how would I modify the rollapplyr function? Also how is rollapplyr different from rollapply? – qwer May 17 '15 at 07:19