R provides different constructs for grouping together expressions: semicolons, parentheses, and curly braces.

You can write a series of expressions on separate lines:

>x <- 1>y <- 2>z <- 3

Alternatively, you can place them on the same line, separated by semicolons:

`> `**x <- 1; y <- 2; z <- 3**

The parentheses notation returns the result of evaluating the expression inside the parentheses:

()`expression`

The operator has the same precedence as a function call. In fact, grouping a set of expressions inside parentheses is equivalent to evaluating a function of one argument that just returns its argument:

>2 * (5 + 1)[1] 12 ># equivalent expression>f <- function (x) x>2 * f(5 + 1)[1] 12

Grouping expressions with parentheses can be used to override the default order of operations. For example:

>2 * 5 + 1[1] 11 >2 * (5 + 1)[1] 12

Curly braces are used to evaluate a series of expressions (separated by new lines or semicolons) and return only the last expression:

{;`expression_1`

; ...`expression_2`

}`expression_n`

Often, curly braces are used to group a set of operations in the body of a function:

>f <- function() {x <- 1; y <- 2; x + y}>f()[1] 3

However, curly braces can also be used as expressions in other contexts:

`> `**{x <- 1; y <- 2; x + y}**
[1] 3

The contents of the curly braces are evaluated inside the current
environment; a new environment is created by a function call but
*not* by the use of curly braces:

`> `**# when evaluated in a function, ...**

Start Free Trial

No credit card required