openlang

How R handles repeated arithmetic signs

I mistakenly put an extra + into my R code and found that it raised no complaint whatsoever.

Actually, after trying a few more things, I found R behaves rather strangely if several operators appear together.

Could somebody explain the reason, and which operations get evaluated first?


6 + 2
#> [1] 8

6 +++ 2
#> [1] 8

6 --- 2
#> [1] 4

6 +-+ 2
#> [1] 4

6 -+- 2
#> [1] 8

The conversation continues 2

Follow the reasoning
  1. Permalink
    
    lobstr::ast(6 +++ 2)
    #█─`+` 
    #├─6 
    #└─█─`+` 
    #  └─█─`+` 
    #    └─2

    Every operator after the initial one is treated as unary, meaning the function-call equivalent is +(6, +(+(2))).

  2. Permalink

    R allows +/- to serve as unary or binary operators, with unary taking precedence. so the initial sign is the actual binary operation, while the remaining signs form nested unary +/- operations on the right-hand number. unary + leaves it unchanged, unary - reverses its sign each time.

    so 6 +++ 2 amounts to 6 + (+(+2)) = 8, while 6 --- 2 becomes 6 - (-(-2)) = 4. the remaining two sequences work similarly, count the minus signs after the first operator (even means positive, odd means negative).

Other sides of the same question

  1. Getting the present time as a seconds timestamp?

    In Dyalog APL, the function ⎕TS provides today's current year, month, day, hours, minutes, seconds and so on, but can I obtai…

    Replies 2Latest activity apl
  2. Swift - Making integers positive

    can an integer be converted to its absolute value? for instance I tried UInt() already, thinking it would turn the Int into a…

    Replies 4Latest activity swift
  3. Trouble drawing a correlation chart

    Hi folks, Could somebody explane why the Performance Analytics package's chart.Correlation function fails on the iris data, i…

    Replies 3Latest activity r