2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

tidyverseの経過を出力してくれるtidylogをアレンジする

Posted at

tidylogとは

tidylogという面白便利ツールがあります。
tidyverseはとっても便利ですが、今どこが実行されているか知りたい、実際どんな流れでどんな処理が行われているか知りたい、という場合にそれを出力してくれるのがtidylogです。

install.packages('tidylog')
library(tidylog)

data <- mtcars %>% 
  select(mpg, cyl, hp, am) %>% 
  filter(mpg > 15) %>% 
  mutate(mpg_round = round(mpg)) %>% 
  group_by(cyl, mpg_round, am) %>% 
  tally() %>% 
  filter(n >= 1)

library(tidyverse) の代わりに用いることで、select() でどの列を省いたかだとか、filter() で何行削ったかなどを教えてくれます。

image.png

tidylogの出力をアレンジする

せっかくなので何時にどの処理が終わったか知りたいと思い、書いてみました。

library("crayon") # 出力の文字色を変えるためのライブラリ

with_time <- function(x) {
    out = str_c(green$bold(  # 時刻を緑色で表示する
                  Sys.time() %>% as.POSIXct("Asia/Tokyo") %>% format("%Y-%m-%d %H:%M:%S$")
                ), " ", x)
    message(out)  # catでなくmessageを使うことで、順次出力されるようにする
}
options("tidylog.display" = list(with_time))  # 設定を適用

tidylog.gif

ポイントとしては、(1)関数の引数(ここではxにデフォで出力される内容)が入ってくること、(2)message関数を用いることで、各処理が終わったタイミングで出力してくれるようにすることです。

元の設定に戻す際は、options("tidylog.display" = NULL) とします。

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?