R在i + 1:5表达式上的for循环不一致 [英] for-loop inconsistencies in R on i+1:5 expression

查看:156
本文介绍了R在i + 1:5表达式上的for循环不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管这不是一个好习惯,但我正在使用double for循环执行计算.为了说明我得到的错误,下面的for循环可以实现.为什么内部for循环中的'j'计数器超过'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

推荐答案

为什么内部for循环中的'j'计数器超过'5'?

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

for(j in i+1:5)等同于for(j in i+(1:5)),可以依次开发为for(j in (i+1):(i+5))

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 ### 

我在这里感兴趣的运算符上添加了###,序列的优先级高于 binary add ,因此将i添加到计算完整个序列.

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.

如果希望保持在(i+1):5范围内,则必须注意一个特殊情况,其中i5,因为您的序列将变为6:5.

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))
    }
}

哪个输出:

[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在i + 1:5表达式上的for循环不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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