Why should someone use {} for initializing an empty object in R?

后端 未结 2 1156
野性不改
野性不改 2020-12-16 16:33

It seems that some programmers are using:

a = {}
a$foo = 1
a$bar = 2

What is the benefit over a = list(foo = 1, bar = 2)?

2条回答
  •  借酒劲吻你
    2020-12-16 16:47

    Per R's documentation on braces and parentheses (type ?'{' to read them), braces return the last expression evaluated within them.

    In this case, a <- {} essentially "returns" a null object, and is therefore equivalent to a <- NULL, which establishes an empty variable that can then be treated as a list.

    Incidentally, this is why it is possible to write R functions in which the function's output is returned simply by writing the name of the returned variable as the function's final statement. For example:

    function(x) {
        y <- x * 2
        return(y)
    }
    

    Is equivalent to:

    function(x) {
        y <- x * 2
        y
    }
    

    Or even:

    function(x) {
        y <- x * 2
    }
    

    The final line of the function being an assignment suppresses printing of the result in the console, but the function definitely returns the expected value if it saved into a variable.

提交回复
热议问题