简体   繁体   English

如何在RStudio中提供整洁的R控制台更新消息?

[英]How to provide a tidy R console update message in RStudio?

This code lets me leave a nice message (on Windows) in the R console, without fill up the screen: 这段代码让我在R控制台中留下了一个很好的消息(在Windows上),而没有填满屏幕:

imax <- 2000
for (i in seq_len(imax)) {
    mess <- sprintf("slightly different length message: %i", i)
    message(paste(rep("\b", nchar(mess)), collapse = ""), appendLF = FALSE)
    message(mess, appendLF = i == imax)
    flush.console()
}

In RStudio the backspace character doesn't work and I get horrible appended messages everywhere. 在RStudio中,退格字符不起作用,我到处都收到可怕的附加消息。

How can I do this nicely in both Rgui and RStudio? 我怎样才能在Rgui和RStudio中做得很好?

What about cross-platform? 跨平台怎么样?

Do you require the actual values/message or are you just trying to show progress? 您是否需要实际值/消息,或者您只是想显示进度?

If it's the latter, txtProgressBar() might be enough: 如果是后者,则txtProgressBar()可能就足够了:

imax <- 2000
msg <- txtProgressBar(min=1, max=length(seq_len(imax)), initial=1)
for (i in seq_len(imax)) {
  setTxtProgressBar(msg, i)
  Sys.sleep(0.001) # so it will show something vs just fly through the loop
}
close(msg)

If you need the values/message and are OK with just not having it be an actual diagnostic message, then cat should do it: 如果您需要值/消息并且没有它是实际的诊断消息就可以了,那么cat应该这样做:

imax <- 2000
for (i in seq_len(imax)) {
  mess <- sprintf("slightly different length message: %i", i)
  cat(paste(rep("\b", nchar(mess)), collapse = ""))
  cat(mess)
  if (i == imax) { cat("\n") }
  Sys.sleep(0.001) # again, loop is too fast to show w/o a delay
}

EDIT/addition from original submission: 原始提交的编辑/添加:

Did some additional testing and it's the output to stderr that's causing the different behavior in RStudio's console area. 做了一些额外的测试,它是stderr的输出导致RStudio控制台区域的不同行为。 When I call .makeMessage directly and then use cat with output going to stdout vs stderr it works: 当我直接调用.makeMessage然后使用带输出的cat转到stdout vs stderr它可以工作:

imax <- 2000
for (i in seq_len(imax)) {
  mess <- sprintf("slightly different length message: %i", i)
  cat(.makeMessage(paste(rep("\b", nchar(mess)), collapse = ""), domain=NA, appendLF = FALSE))
  cat(.makeMessage(mess, domain=NA, appendLF = (i == imax)))
  Sys.sleep(0.001) # delay...see above snippets
  flush.console()
}

add file=stderr() to the cat 's and it will behave the way the original message call does. file=stderr()添加到cat ,它的行为与原始message调用的方式相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM