Search code examples
rif-statementprintingexpressioncompound-assignment

Different results for if-else expression in R


I am getting different results for changings order of "d + 20" and "print("d is smaller than 100")" within if-else in R. Please see the code below and help explain the difference.

As far as I know, value of a compound expression is the value of the last expression, but this does not help explain this case:

Code #1:

d <- 12
if (d > 100) {
    print("d is greater than 100")
} else {
    d + 20
    print("d is smaller than 100")
}
Result:
[1] "d is smaller than 100"

Code #2:

d <- 12
if (d > 100) {
    print("d is greater than 100")
} else {
    print("d is smaller than 100")
    d + 20
}
Result:
[1] "d is smaller than 100"
[1] 32

Solution

  • If else statements return by default the last expression. All other expressions are also being evaluated but not being returned (or saved) in this example:

    if(TRUE){
      1+1
      2+2
      3+3
    }
    
    Result:
    [1] 6
    

    If you wrap expressions into print() statements they will also all be evaluated (like above) which prints them to the console.

    if(TRUE){
      print(1+1)
      print(2+2)
      print(3+3)
    }
    
    Result:
    [1] 2
    [1] 4
    [1] 6
    

    Besides printing the value to the console, print() statements also return the argument but in an invisible manner. The primary effect of print() is displaying it to the console, but the function will also return the argument invisibly without printing it again to the console. In your code example 1

    d <- 12
    if (d > 100) {
        print("d is greater than 100")
    } else {
        d + 20
        print("d is smaller than 100")
    }
    Result:
    [1] "d is smaller than 100"
    

    only "d is smaller than 100" is being printed as a result of the execution of the print() statement, since the last expression which is being returned is the invisible return of the print() statement and not the d + 20 expression. The d + 20 expression will be evaluated just like the 1+1 and 2+2 in my first example, but it won't be returned since it is not the last expression in the block. The last expression is the invisible return of print().

    I hope this makes sense!