0

I formulate my question by the following simple code. The elements of vector a were initially assigned to be 0, and we use a for loop to reassign values. All the elements of a are supposed to be 1. However, the 7-th element is unchanged. Can anyone explain why this happens in R.

> (s = seq(0.01,.1,0.01))
 [1] 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10
> (a = rep(0,length(s)))
 [1] 0 0 0 0 0 0 0 0 0 0
> for (i in s)  a[i*100] = 1
> a
 [1] 1 1 1 1 1 1 0 1 1 1
K. Huang
  • 13
  • 4

1 Answers1

1

Some sort of floating point rounding magic. See:

as.integer(s[7]* 100)
# [1] 6
# as.integer(s * 100)
# [1]  1  2  3  4  5  6  6  8  9 10

So that 7th index is actually 6.

It is safer to loop over integers and index in to s rather than relying on casting floating-point things to integer.

for (i in seq_along(s))
    a[i] = 1 # or possibly something involving s[i] for your application
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194