对于R中的“循环不一致” [英] 'For' loop inconsistencies in R

查看:135
本文介绍了对于R中的“循环不一致”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然这不是一个好的做法,但我正在使用double for循环来执行计算。为了说明我得到的错误,下面的for循环会做。为什么j计数器在内循环中超过5?

 > (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 更高的优先级,所以添加 i 如果你希望保持在(i + 1)的范围内:5

/ code>你必须照顾一个特殊情况,其中 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


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

解决方案

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

这篇关于对于R中的“循环不一致”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆