'for loop and if statement in R
I am running the below R code
n = 2
for(i in 1:n){
if(i+1 <= n){
for(j in i+1:n){
print(j)
}
}
}
I expect the outcome to be
[1] 2
but in fact I am getting
[1] 2
[1] 3
I am not sure where this 3 comes from. I ran the counterpart python/matlab codes, and I am getting the expected output.
Solution 1:[1]
try for(j in (i+1):n){
you want j to go from 2:2, but right now, you let j go from 1 + the numeric vector 1:2.
R differs with python/matlab in how it handles vectors (as you can see below)
try in your console and see how it works
1 + 1:2
and
(1 + 1):2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wimpel |
