rvariable-assignment

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)


Solution

  • 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)}