[R] for loop problem
Tobias Verbeke
tobias_verbeke at skynet.be
Mon Jul 14 10:32:57 CEST 2003
Dear list,
Here's a function that works fine
when I assign one value to i.
qx, ax and gr are vectors.
ax.to.nax <- function(qx, ax, gr=c(0,1,5,10)){
px <- 1 - qx
last.n <- gr[length(gr)] - gr[length(gr) - 1]
all.bounds <- c(gr, gr[length(gr)] + last.n)
n <- diff(all.bounds)
#
i <- 1 # this i should loop through the values of
# gr: i=0, i=1, i=5 and i=10.
#
testprod <- prod(px[(i+1):(i+n[i+1])])
return(1 - testprod)
}
Every attempt to loop through
the values of gr, gives the following
error message:
Error in (i + 1):(i + n[i + 1]) : NA/NaN argument
Here is an example of the deplorably
erroneous code that causes the message
to appear:
ax.to.nax.for <- function(qx, ax, gr=c(0,1,5,10)){
px <- 1 - qx
last.n <- gr[length(gr)] - gr[length(gr) - 1]
all.bounds <- c(gr, gr[length(gr)] + last.n)
n <- diff(all.bounds)
testprod <- numeric(length(gr))
for (j in 1:length(gr)){
i <- gr[j]
testprod[j] <- prod(px[(i+1):(i+n[i+1])])
}
return(1 - testprod)
}
In what way am I ill-treating R ?
Thanks in advance,
Tobias
More information about the R-help
mailing list