2

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.

2
  • 2
    try: (for j in (i+1):n) Commented Apr 7, 2022 at 15:00
  • 2
    Chapter 8.1.3 of The R Inferno Commented Apr 7, 2022 at 15:01

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.