R on i + 1:5表达式中的for循环不一致性

Ang*_*dre 1 for-loop r

虽然这不是一个好习惯,但我使用双循环来执行计算.为了说明我得到的错误,以下for循环可以做到.为什么内部for循环中'j'计数器超过'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
Run Code Online (Sandbox Code Playgroud)

Ten*_*bai 8

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

for(j in i+1:5)相当于for(j in i+(1:5))可以反过来发展到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 ### 
Run Code Online (Sandbox Code Playgroud)

我将###添加到我们感兴趣的运算符中,序列的优先级高于二进制add,因此i一旦计算完成,就会对整个序列进行添加.

如果您希望保留的范围(i+1):5,你必须采取特殊的情况下,其中的护理i5因为您的序列将成为6:5.

所以最后你的代码可能是:

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

哪个输出:

[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
Run Code Online (Sandbox Code Playgroud)

  • @BenBolker因为我不是R专家并且玩很多语言我试着保持通用样式,每种语言都允许这种情况,所以*如果条件赋值其他任务*通常更容易从语言中删除到语言:) (3认同)