チラシの裏の落書き日記

統計とか,研究とか,日常についての備忘録的なもの。

Rの出力の色などを変更したい+forなどの繰り返し出力を1行で表示したい

GitHubにある,crayonパッケージを使えば簡単


github.com


詳しくはヘルプを見たり,exampleを走らせればすぐにわかる。
簡単に使えるので,良さそう。

  library(crayon)
  cat(blue("Hello", "world!\n"))

# Crayon defines the %+% string concatenation operator, to make it easy to assemble stings with different styles.

  cat("... to highlight the " %+% red("search term") %+%
      " in a block of text\n")
# Styles can be combined using the $ operator:

  cat(yellow$bgMagenta$bold('Hello world!\n'))
# See also combine_styles().

# Styles can also be nested, and then inner style takes precedence:

  cat(green(
    'I am a green line ' %+%
    blue$underline$bold('with a blue substring') %+%
    ' that becomes green again!\n'
  ))
It is easy to define your own themes:

  error <- red $ bold
  warn <- magenta $ underline
  note <- cyan
  cat(error("Error: subscript out of bounds!\n"))
  cat(warn("Warning: shorter argument was recycled.\n"))
  cat(note("Note: no such directory.\n"))

# See Also
# make_style() for using the 256 ANSI colors.

# Examples

cat(blue("Hello", "world!"))

cat("... to highlight the " %+% red("search term") %+%
    " in a block of text")

cat(yellow$bgMagenta$bold('Hello world!'))

cat(green(
 'I am a green line ' %+%
 blue$underline$bold('with a blue substring') %+%
 ' that becomes green again!'
))

error <- red $ bold
warn <- magenta $ underline
note <- cyan
cat(error("Error: subscript out of bounds!\n"))
cat(warn("Warning: shorter argument was recycled.\n"))
cat(note("Note: no such directory.\n"))


下のコードを実行すると,iの繰り返しに伴った主力が1行で更新されながら表示される。
(通常は,繰り返しごとに1行出力する。)
ポイントは,flush.console()と,cat関数の頭にある"\r" これでOK。
反復アルゴリズムの途中経過の出力をしたい場合には,よい。

for(i in 1:10) {
  cat("\r i = ",i, ": ",format(Sys.time(),"%H:%M:%S"))
  Sys.sleep(0.5)
  flush.console() 
}