Assign and Print
I just stumbled upon this neat little R pattern which I found really nice/helpful. I was assigning and evaluating some expressions, but I also wanted to see what values I was getting. Toy example:
1set.seed(0)
2x <- runif(10)
3x
4#> [1] 0.8966972 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819 0.8983897
5#> [8] 0.9446753 0.6607978 0.6291140
6xbar <- mean(x)
7xbar
8#> [1] 0.635005
I was working in a script, so I was just mashing Ctr + Enter
a few times to run the above snippet. Obviously in a notebook such a command could be condensed to just the chord for Run Cell
, but my point will stand.
You can rewrite the above like this:
1set.seed(0)
2x <- runif(10)
3print(x)
4#> [1] 0.8966972 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819 0.8983897
5#> [8] 0.9446753 0.6607978 0.6291140
6xbar <- mean(x)
7print(xbar)
8#> [1] 0.635005
but this is unnecessary since evaluating x
will print it. I was thinking about this when I remembered that print
returns invisibly. This allows you to condense above to just:
1set.seed(0)
2x <- runif(10) |> print()
3#> [1] 0.8966972 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819 0.8983897
4#> [8] 0.9446753 0.6607978 0.6291140
5xbar <- mean(x) |> print()
6#> [1] 0.635005
I think this looks a lot nicer.
I popped it into a small snippet as well, just for kicks.
1{
2 "Evaluate and Print": {
3 "prefix": "eprint",
4 "body": "|> print()",
5 "description": "Piped input gets printed and returned invisibly; useful for printing an expression and assigning it."
6 }
7}
All R snippets above created on 2025-02-23 with reprex v2.1.1