对于R中的“循环不一致” [英] 'For' loop inconsistencies in R
问题描述
> (i(i,j))
+}
[1(5)) ] 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
为什么j内部计数器在内循环中超过了'5'?
原因可以在这里找到
$ b (i + 1:5)中的(j在i + 1:5中)相当于 code>,它可以转化为
(j在(i + 1):( i + 5))中的元素
定义了下面的一元和二元运算符。它们按照从高到低的顺序排列。
:: :::访问命名空间中的变量
$ @组件/槽提取
[[[indexing
^幂(右至左)
- +一元减号和加号
:序列运算符###
%任何特殊运算符(包括%%和%/%)
* /乘除法
+ (binary)add,subtract ###
##给我们这里感兴趣的操作符,序列比二进制add 更高的优先级,所以添加 / code>你必须照顾一个特殊情况,其中 最后你的代码可以是: 输出: 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?
Why is the 'j' counter exceeding '5' in the inner for loop? The reason can be found here i
如果你希望保持在(i + 1)的范围内:5
i
是 5
成为 6:5
。
pre $ for(i in 1:5){
s < - min(i + 1,5)#Per Ben Bolker comment
for(j在s:5){
print(c(i,j))
}
}
[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
> 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
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 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
这篇关于对于R中的“循环不一致”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!