Home > Blockchain >  Odd vector loop behaviour in R
Odd vector loop behaviour in R

Time:04-17

I'm trying to 'slice' a descending sequence of elements from a list, like so:

test <- c(1:10)
for (i in test){
print(i:test[length(test)])
}

The output is:

 [1]  1  2  3  4  5  6  7  8  9 10
[1]  2  3  4  5  6  7  8  9 10
[1]  3  4  5  6  7  8  9 10
[1]  4  5  6  7  8  9 10
[1]  5  6  7  8  9 10
[1]  6  7  8  9 10
[1]  7  8  9 10
[1]  8  9 10
[1]  9 10
[1] 10

However, I am getting an odd output when floats are in the list.

test <- c(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.1)

 [1]  1.1  2.1  3.1  4.1  5.1  6.1  7.1  8.1  9.1 10.1
[1] 2.2 3.2 4.2 5.2 6.2 7.2 8.2 9.2
[1] 3.3 4.3 5.3 6.3 7.3 8.3 9.3
[1] 4.4 5.4 6.4 7.4 8.4 9.4
[1] 5.5 6.5 7.5 8.5 9.5
[1] 6.6 7.6 8.6 9.6
[1] 7.7 8.7 9.7
[1] 8.8 9.8
[1] 9.9
[1] 10.1

As you can see, many of the elements output weren't in the original vector. This behavior gets even stranger when my actual data set is use (around 90 elements, all of which are floats), when several elements are output multiple times, with a lot of N/A's. A quick chunck of the output is:

 [1] 13.90370 13.96806 13.99962 14.05951 14.11134 14.15238 14.18557 14.22471 14.27834 14.30811 14.36219 14.40581
 [13] 14.43922 14.48592 14.52759 14.56241 14.59632 14.63917 14.66668 14.69875 14.74036 14.77602 14.81268 14.83571
 [25] 14.86539 14.90646 14.94870 14.97308 15.00642 15.03577 15.06180 15.08710 15.12115 15.14261 15.17206 15.19136
 [37] 15.21572 15.22627 15.25308 15.28468 15.30114 15.33367 15.35086       NA       NA       NA       NA       NA
 [49]       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA
 [61]       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA

What is going on here?

CodePudding user response:

We need to loop over the sequence instead of the values of 'test'. In the first case, it worked because the values are the sequence, which is not the case with the second 'test'

for(i in seq_along(test)) print(test[i:length(test)])

-output

[1]  1.1  2.2  3.3  4.4  5.5  6.6  7.7  8.8  9.9 10.1
[1]  2.2  3.3  4.4  5.5  6.6  7.7  8.8  9.9 10.1
[1]  3.3  4.4  5.5  6.6  7.7  8.8  9.9 10.1
[1]  4.4  5.5  6.6  7.7  8.8  9.9 10.1
[1]  5.5  6.6  7.7  8.8  9.9 10.1
[1]  6.6  7.7  8.8  9.9 10.1
[1]  7.7  8.8  9.9 10.1
[1]  8.8  9.9 10.1
[1]  9.9 10.1
[1] 10.1

i.e. when we do the : by the values, it is incrementing by 1

> 1.1:test[length(test)]
 [1]  1.1  2.1  3.1  4.1  5.1  6.1  7.1  8.1  9.1 10.1
> 2.2:test[length(test)]
[1] 2.2 3.2 4.2 5.2 6.2 7.2 8.2 9.2
> 3.3:test[length(test)]
[1] 3.3 4.3 5.3 6.3 7.3 8.3 9.3

It is mentioned in the ?":"

For other arguments from:to is equivalent to seq(from, to), and generates a sequence from from to to in steps of 1 or -1.

Therefore, it is not an odd behavior.

  • Related