[R] for loop problem

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Mon Jul 14 11:56:27 CEST 2003


Tobias Verbeke <tobias_verbeke at skynet.be> writes:

> 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 ?

You're ill-treating the readers by not giving a full example of a call
to the function... However: in the for loop, i will be one of 0,1,5,10
and n is the vector c(1,4,5,5) so n[i+1] is indexing out of bounds and
e.g. 

> n[6]
[1] NA

and the : operator subsequently objects. Did you mean (i+1):(i+n[j]+1)
or so? 

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list