Home > OS >  for loop and if statement in R
for loop and if statement in R

Time:04-13

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.

CodePudding user response:

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
  • Related