# [R] data manipulation, tapply

Michaell Taylor pols1oh at bestweb.net
Wed Jun 5 22:59:40 CEST 2002

```
I have a tricky (for me) tapply sort of problem for which I am searching for
the a computationally efficient solution.

I have a file of historical data which looks like:

yr	deflator	price
1990	.03		5.12
1991	.023		5.09
.
.
.
2001	.068		7.8

(deflator is for a highly specialized basket of goods if you are confused by
those numbers)

I also have a 50000 scenario monte carlo forecast simulation which looks
somthing like:

scenario 	yr	deflator	price
1		2002	.014		8.2
1		2003	.032		8.5
.
.
1		2011	.041		15.3
.
.
50000		2011	.078		6.23

Each of the 50000 scenarios contains 10 years of forecasts. Now I would like
to create a measure of deviation from the moving 10-year inflation adjusted
average for each scenario.  For the first 9 years of the monte carlo (mc)
data, the historical dataset will need to be referenced to achieve the full
10 years worth of data.

One way to go would be to prepend the history to the mc data 50000 times so
that the history would precede each scenario. Easy to code, but not too
efficient.

A single scenario version might look something like this:

rentvect <- c(hisren,mcren)
lv <- length(rentvect)
rentvect <- rentvect[(lv-10):lv]
infvect <- c(hisinf,mcinf)
lv <- length(infvect)
infvect <- infvect[(lv-9):lv]
infvect <- c(1,infvect)
realrent_mean(rentvect/cumprod((lv)))
return(current/realrent)
}
(should) produces a current rent/moving average ratio.

I initially jotted down this function with the intention of using a tapply to
create scenario by scenario calculations, but suddenly realize that tapply
doesn't really seem to fit (er, my function doesn't fit tapply, rather).

Anyone been down this road? or better was able to find a far better road to
get to the same place.

=========================================
Michaell Taylor, PhD
Senior Economist, Reis, New York, USA
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```