M--
M--

Reputation: 29153

Wrapping assignments in parentheses returns the output of that assignment in console

I was not aware that if you wrap an assignment in parentheses, the value of that assignment will be printed out in the console. See below; what's the reason for this behavior?

a <- 1
b = 2
assign("c", 3)

(a <- 1)
#> [1] 1
(b = 2)
#> [1] 2
(assign("c", 3))
#> [1] 3

Created on 2023-03-01 by the reprex package (v2.0.1)

Upvotes: 1

Views: 238

Answers (2)

M--
M--

Reputation: 29153

Here's an explanation about parenthesis and brace: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Paren.html

Description

Open parenthesis, (, and open brace, {, are .Primitive functions in R.

Effectively, ( is semantically equivalent to the identity function(x) x, whereas { is slightly more interesting, see examples.

Usage

( ... )

{ ... }

Value

For (, the result of evaluating the argument. This has visibility set, so will auto-print if used at top-level.

For {, the result of the last expression evaluated. This has the visibility of the last evaluation.

Examples

f <- get("(")
e <- expression(3 + 2 * 4)
identical(f(e), e)
#> [1] TRUE

do <- get("{")
do(x <- 3, y <- 2*x-3, 6-x-y); x; y
#> [1] 0
#> [1] 3
#> [1] 3

## note the differences
(2+3)
#> [1] 5
{2+3; 4+5}
#> [1] 9
(invisible(2+3))
#> [1] 5
{invisible(2+3)}

Upvotes: 8

Carl Witthoft
Carl Witthoft

Reputation: 21532

This is by design. It's not easy to find it in the documentation, but somewhere there's an explanation that (something_with_output) invokes the 'print' command.

FWIW I find it useful when using closures whose code includes return(invisible(stuff)) .

Upvotes: 2

Related Questions