O'Reilly logo

R in a Nutshell, 2nd Edition by Joseph Adler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Expressions

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

Separating Expressions

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

Parentheses

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

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required