How can I do this better? (Filling in last traded price for NA)
Great email thread in response to Ajay's question! [ I am having some mail
delays at one of the @debian.org mail hosts so I may not have seen all
posts, but I did check the web archive of the list. ]
What is surprising, though, is that nobody looked at _sources_ of its which
has a function locf() to do just this:
#locf-function---------------------------------------------------
locf <- function(x)
{
if (!inherits(x, "its")) stop("function is only valid for objects of class 'its'")
y <- x
jna <- which(apply(is.na(x),2,any))
for(j in jna)
{
y[,j] <- y[most.recent(!is.na(y[,j])),j]
}
return(y)
}
It uses this function
#most.recent-function--------------------------------------------
most.recent <- function(x)
{
# return a vector of indices of the most recent TRUE value (thanks to Tony Plate)
if (!is.logical(x)) stop("x must be logical")
x.pos <- which(x)
if (length(x.pos)==0 || x.pos[1] != 1) x.pos <- c(1, x.pos)
rep(x.pos, c(diff(x.pos), length(x) - x.pos[length(x.pos)] + 1))
}
Would anybody care to time the different approaches we've seen submitted?
Regards,
Dirk
(who, before the list existed, had asked Giles about this)
Those are my principles, and if you don't like them... well, I have others.
-- Groucho Marx