[R-sig-finance] How can I do this better? (Filling in last traded
price for NA)
Gabor Grothendieck
ggrothendieck at myway.com
Mon Sep 13 13:29:01 CEST 2004
This is referred to as LOCF, last observation carried forward.
First create some test data -- we are using ts here but using
its would be analogous:
v1 <- c(1, NA, NA, 2, 3, NA, 5)
v2 <- rev(v1)
vv <- ts.union(ts(v1), ts(v2, start = 2))
Now define LOCF as a function and apply it:
LOCF <- function(v) {
L <- !is.na(v)
v[c(NA,which(L))[cumsum(L)+1]]
}
apply(vv, 2, LOCF)
Date: Sun, 12 Sep 2004 21:03:36 +0530
From: Ajay Shah <ajayshah at mayin.org>
To: r-sig-finance <r-sig-finance at stat.math.ethz.ch>
Subject: [R-sig-finance] How can I do this better? (Filling in last traded price for NA)
I have 3 different daily time-series. Using union() in the "its"
package, I can make a long matrix, where rows are created when even
one of the three time-series is observed:
massive <- union(nifty.its, union(inrusd.its, infosys.its))
Now in this, I want to replace NA values for prices by the
most-recently observed price. I can do this painfully --
for (i in 2:nrow(massive)) {
for (j in 1:3) {
if (is.na(massive[i,j])) {
massive[i,j] = massive[i-1,j]
}
}
}
But this is horribly slow. Is there a more clever way?
--
Ajay Shah Consultant
ajayshah at mayin.org Department of Economic Affairs
http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
More information about the R-sig-finance
mailing list