When writing the code in data.table format as shown below
Is there a possible way of making sure that when I use the RStudio code reformatter cmd + shift + A, the code is formatted as above, instead of as shown below;
Not going the direction you want it to (offset stacking), but one way of neatly 'stacking' your chained calls is to use base R's |> pipe (added in R 4.1) and _ placeholder (added in R 4.3) to make your subsequent calls indent neatly across lines. e.g.:
dt |>
_[do this] |>
_[then this] |>
_[and finally this]
That's more along styler's lines. The pipe and _ don't add any extra steps as R parses them as if chained in normal syntax:
library(data.table)
mtcars_dt <- as.data.table(mtcars)
expr <- quote(mtcars_dt |>
_[, .N, by = .(cyl)] |>
_[order(-N)] |>
_[, .(mean = mean(N), sd = sd(N))])
expr
#> mtcars_dt[, .N, by = .(cyl)][order(-N)][, .(mean = mean(N), sd = sd(N))]
eval(expr)
#> mean sd
#> 1: 10.66667 3.511885
Error: pipe placeholder can only be used as a named argument.|> pipe chain - it essentially reads the stacked lines as a set of chained square brackets exactly as the normal syntax would be written and evaluates accordingly._ in this fashion ... reinforcing SamR's "4.3" comment, but dang that's smooth!quote() or substitute() functions shows the exact source code non-piped equivalent of the original code compared to using expression() function that prepends the output with expession. The output of quote(mtcars_dt |> _[, .N, by = .(cyl)]) or substitute(mtcars_dt |> _[, .N, by = .(cyl)]) is mtcars_dt[, .N, by = .(cyl)] while the output of expression(mtcars_dt |> _[, .N, by = .(cyl)]) is expression(mtcars_dt[, .N, by = .(cyl)]). The output using quote/substitute looks a bit cleaner
stylerpackage, which "only support[s] the tidyverse style guide and I don't see this formatting compatible with it" github.com/r-lib/styler/issues/720#issuecomment-769711869. See that comment for possible hacks to get what you want.