Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

for-loop inconsistencies in R on i+1:5 expression

Although it is not a good practice, I am using a double for loop to perform a calculation. To illustrate the error I am getting, the following for loop would do. Why is the 'j' counter exceeding '5' in the inner for loop?

> for(i in 1:5){
+   for(j in i+1:5)
+     print(c(i,j))
+ }
[1] 1 2
[1] 1 3
[1] 1 4
[1] 1 5
[1] 1 6
[1] 2 3
[1] 2 4
[1] 2 5
[1] 2 6
[1] 2 7
[1] 3 4
[1] 3 5
[1] 3 6
[1] 3 7
[1] 3 8
[1] 4 5
[1] 4 6
[1] 4 7
[1] 4 8
[1] 4 9
[1] 5 6
[1] 5 7
[1] 5 8
[1] 5 9
[1]  5 10
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why is the 'j' counter exceeding '5' in the inner for loop?

for(j in i+1:5) is equivalent of for(j in i+(1:5)) which can in turn be developed to for(j in (i+1):(i+5))

The reason can be found here

The following unary and binary operators are defined. They are listed in precedence groups, from highest to lowest.

:: :::    access variables in a namespace
$ @   component / slot extraction
[ [[  indexing
^ exponentiation (right to left)
- +   unary minus and plus
: sequence operator ###
%any% special operators (including %% and %/%)
* /   multiply, divide
+ -   (binary) add, subtract ### 

I added the ### to the operators which interest us here, the sequence is of higher precedence than the binary add so adding i will be done to the whole sequence once it has been computed.

If you wish to keep in the range (i+1):5 you have to take care of a special case, where i is 5 as your sequence will become 6:5.

So finally your code could be:

for (i in 1:5){
    s <- min(i+1,5) # Per Ben Bolker comment
    for (j in s:5) {
      print(c(i,j))
    }
}

Which output:

[1] 1 2
[1] 1 3
[1] 1 4
[1] 1 5
[1] 2 3
[1] 2 4
[1] 2 5
[1] 3 4
[1] 3 5
[1] 4 5
[1] 5 5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...