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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…