[R] Problem (bug?) with vector indices
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Tue Aug 31 22:25:37 CEST 2004
"Rodrigo Drummond" <rduarte at unicamp.br> writes:
> Hi all,
>
> I found a problem on R that looks like a bug to me. I am working with R
> for windows verson 1.9.0, but the problem also happens on the linux
> version 1.9.0. I hope that the problem is on my reasoning, and I would be
> grateful if someone could explain me why this happens.
> There goes the example:
>
> > x<-seq(-2,2,0.001)
> > y<-rep(0,length(x))
> > for (i in x){y[1000*i+2001]<-i^2}
...
> > x[244]
> [1] -1.757
> > i<-x[244]
> > 1000*i+2001
> [1] 244
> > y[1000*i+2001]
> [1] 3.087049
> > y[244]
> [1] 0
> > y[243]
> [1] 3.087049
>
>
> What means that the expression 1000*i+2001, which is equal to 244, inside
> the brackets is evaluated as 243! The same occurs with every value of x
> that results in a zero value of y, the right value is stored in y one
> position before it should be, overwriting the previous value at this
> position.
> The bug is on R or on my mind?
The latter:
Have a look at (1000*x[244]+2001)-244
Beware floating point arithmetic!
--
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