是否有一种更简单的方法可以使用R中的cat擦除行尾?

时间:2012-04-18 22:08:45

标签: r

我喜欢在我的脚本中使用它:

cat("Saving...")
do_something_slow()
cat("\rSaved\n")

问题是在不删除剩余行的情况下应用回车符,所以我明白了:

Savedg...

为了解决这个问题,我可以这样做:

cat("\rSaved\033[K\n")

但它有点难看。有更简单的方法吗?

2 个答案:

答案 0 :(得分:4)

我喜欢使用message()代替cat()来生成消息。例如:

cat("Saving..."); cat("\rSaved\n")

返回:

Savdg...

虽然:

message("Saving..."); message("\rSaved\n")

返回:

Saving...
Saved

修改

受@gauden回答的启发,另一个功能可能是:

replaceMessage <- function(x, width = 80)
{
    message("\r", rep(" ", times = width - length(x)), "\r", appendLF = F)
    message(x, appendLF = F)
}

然后:

replaceMessage("Saving..."); Sys.sleep(1); replaceMessage("Saved\n")

注意:

虽然replaceMessage()在Windows上的Linux和Rterm中表现如预期,但它在我的Rgui(2.15.0,Windows x64)中表现得很奇怪。具体来说,永远不会显示Saving...,并且在显示Saved之后,光标会向右移动width个空格(在本例中为80个空格)。我不知道为什么。

答案 1 :(得分:4)

假设您希望所有消息都在一行上串行显示,那么异想天开的怎么样?

cleancat <- function(astring, width=80) {
    # Reserves a line of 80 (default) characters
    # and uses it for serial updates
    require("stringr")
    astring <- paste("\r", astring, sep="")
    cat(str_pad(astring, 80, "right"))
    # pretend to do something slow
    # delete this line if cleancat is used in production
    Sys.sleep(0.5) 
}

# imitate printing a series of updates
test <- lapply(c("Saving -", 
                 "Saving \\", 
                 "Saving |", 
                 "Saving /", 
                 "Saving -", 
                 "Saving \\", 
                 "Saving |", 
                 "Saving /", 
                 "Saved"), cleancat)

当然,您需要加载stringr包,并在您的环境中设置cleancat功能,您可能认为这个功能更加丑陋......