Introduction

If you have ever accidentally typed an extra plus or minus sign in your R script, you might have expected R to throw a syntax error. Surprisingly, expressions like 4 +++ 1 or 4 --- 1 execute cleanly without any warnings. But why does this happen, and what rules dictate how R evaluates these chained operators?

In this article, we will break down R's parsing behavior, operator precedence, and how R distinguishes between binary and unary operators to produce these results.

Unary vs. Binary Operators in R

To understand what is happening under the hood, we first need to distinguish between two types of arithmetic operators:

  • Binary Operators: Operators that require two operands, performing operations like addition or subtraction between them (e.g., a + b).
  • Unary Operators: Operators that act on a single operand to indicate positive or negative sign (e.g., +1 or -1).

When you chain operators together like 4 +++ 1, R's parser treats the first operator as a binary operator connecting the left operand (4) to the rest of the expression. The subsequent operators are parsed as a series of unary operators applied to the right operand (1).

Step-by-Step Breakdown of Chained Operators

Let's look at how R parses and evaluates each example from right to left for unary signs, and then performs the binary operation:

1. 4 +++ 1 (Result: 5)

R interprets this expression as: