tidyオプションのコード整形の比較

Last Updated on 2024年5月4日 by 三竹道雄

tidy オプションのコード整形の比較

Quarto のチャンクオプション tidystyler とした場合と formatRとした場合の出力の整形を比較します。

参考資料は https://gedevan-aleksizde.github.io/rmarkdown-cookbook/opts-tidy.html です。

始めにそれぞれのパッケージのバージョンを確認します。

packageVersion("styler")
[1] '1.10.3'
packageVersion("formatR")
[1] '1.14'

整形するコードは以下のコードです。なお、共通して tidy-opts は何も指定せずにデフォルトでの違いを確認します。

function (x, y, ...) 
{
# ggplot2::aes
xs<-arg_enquos("x");ys<-arg_enquos("y");dots<-enquos(...)
args<-c(xs, ys, dots)
args<-Filter(Negate(quo_is_missing),args)
local({aes<-function(x, y, ...) NULL
inject(aes(!!!args))
})
aes<-new_aes(args,env=parent.frame())
rename_aes(aes)
}
# comment 1
# comment 2
# comment 3
library(ggplot2);library(tidyr)
data.frame(n=seq(10),a=rnorm(10),b=rnorm(10))%>%gather(key='key',value='value',colnames(.)[-1])%>%{.$key<-factor(.$key);.}%>% ggplot(mapping=aes(x=n,y=value,col=key))+geom_point()+theme_minimal()+labs(title='title',subtitle='subtitle',caption='caption')

tidy: styler としたときの出力を確認します。

function(x, y, ...) {
  # ggplot2::aes
  xs <- arg_enquos("x")
  ys <- arg_enquos("y")
  dots <- enquos(...)
  args <- c(xs, ys, dots)
  args <- Filter(Negate(quo_is_missing), args)
  local({
    aes <- function(x, y, ...) NULL
    inject(aes(!!!args))
  })
  aes <- new_aes(args, env = parent.frame())
  rename_aes(aes)
}
# comment 1
# comment 2
# comment 3
library(ggplot2)
library(tidyr)
data.frame(n = seq(10), a = rnorm(10), b = rnorm(10)) %>%
  gather(key = "key", value = "value", colnames(.)[-1]) %>%
  {
    .$key <- factor(.$key)
    .
  } %>%
  ggplot(mapping = aes(x = n, y = value, col = key)) +
  geom_point() +
  theme_minimal() +
  labs(title = "title", subtitle = "subtitle", caption = "caption")

続いて tidy: formatR としたときの出力を確認します。

function(x, y, ...) {
    # ggplot2::aes
    xs <- arg_enquos("x")
    ys <- arg_enquos("y")
    dots <- enquos(...)
    args <- c(xs, ys, dots)
    args <- Filter(Negate(quo_is_missing), args)
    local({
        aes <- function(x, y, ...) NULL
        inject(aes(!!!args))
    })
    aes <- new_aes(args, env = parent.frame())
    rename_aes(aes)
}
# comment 1 comment 2 comment 3
library(ggplot2)
library(tidyr)
data.frame(n = seq(10), a = rnorm(10), b = rnorm(10)) %>%
    gather(key = "key", value = "value", colnames(.)[-1]) %>%
    {
        .$key <- factor(.$key)
        .
    } %>%
    ggplot(mapping = aes(x = n, y = value, col = key)) + geom_point() + theme_minimal() +
    labs(title = "title", subtitle = "subtitle", caption = "caption")

2つの出力結果を比較してみますと、formatR のインデントはスペース4つに対して styler は2つ。

formatR では連続したコメント行は1行に纏められていますが styler はそのまま表示されています。

また、formatR では ggplot で関数を繋げていく 「+」記号で改行されませんが styler では改行されています。

以上です。