[R] Possible to use array of spline functions for storing data?
David Winsemius
dwinsemius at comcast.net
Sat Mar 6 17:01:30 CET 2010
Dear listeRs;
I am hoping to provide myself the ability to interpolate mortality
estimates within intervals for a range of conditions and ages. I have
four mortality tables derived from the Society of Actuaries 2001 VBT
tables that contains interval mortality rates by starting age and year
of duration. I would like to flexibly interpolate using a large set
(~4MM) of ages and conditions as input to small number (~300) of
functions, but my toy implementations puzzle me when I examine them,
and I cannot seem to store them properly. Say you start with a vector
of qx's:
> qx = c(.001, .003, 0.005, 0.01, 0.03, 0.06, 0.12, 0.24,0.4, 0.8)
# Now convert to mortality
> mx <- 2*qx/(2-qx)
# And make a spline function
> mspline <- splinefun(mx)
# Works well.
> mspline(5.5)
# [1] 0.04466954
# Examine the spline function
> mspline
function (x, deriv = 0)
{
deriv <- as.integer(deriv)
if (deriv < 0 || deriv > 3)
stop("'deriv' must be between 0 and 3")
if (deriv > 0) {
z0 <- double(z$n)
z[c("y", "b", "c")] <- switch(deriv, list(y = z$b, b = 2 *
z$c, c = 3 * z$d), list(y = 2 * z$c, b = 6 * z$d,
c = z0), list(y = 6 * z$d, b = z0, c = z0))
z[["d"]] <- z0
}
res <- .C("spline_eval", z$method, as.integer(length(x)),
x = as.double(x), y = double(length(x)), z$n, z$x, z$y,
z$b, z$c, z$d, PACKAGE = "stats")$y
if (deriv > 0 && z$method == 2 && any(ind <- x <= z$x[1L]))
res[ind] <- ifelse(deriv == 1, z$y[1L], 0)
res
}
<environment: 0x218874878>
My first puzzlement is the lack of any evidence that this is
particular to the data that was offered to splinefun. Is it all hidden
within <environment: 0x218874878>? My plan had been to convert a set
of about 300 rows of data into 300 spline functions that could be
indexed in an array by gender, smoking status, and age.
Would I be able to create an array of such functions? Testing leaves
me discouraged:
> spline.arr <- array( , dim= c(sex=2, smk=2, age = 65))
> str(spline.arr)
logi [1:2, 1:2, 1:65] NA NA NA NA NA NA ..
# Now attempt to store one function in the first "cell":
> spline.arr[1,1,1] <- mspline
Error in spline.arr[1, 1, 1] <- mspline :
number of items to replace is not a multiple of replacement length
From the help page for array I thought that the possibility of
storing lists within arrays might mean that functions would "fit", but
have I been too expansive in my thinking? Is there an incantation that
would let me store a language object in an array. Lists appear to be
similarly unable to accept a function as an element:
> spl.list <- list()
> spl.list[["M"]][["NS"]][["20"]] <- mspline
Error in spl.list[["M"]][["NS"]][["20"]] <- mspline :
invalid type/length (closure/0) in vector allocation
> spl.list[["M"]][["NS"]][["20"]] <- 1 # no error
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list