你如何格式化多行 R 包消息?

nsh*_*eff 3 string format message r

在开发 R 包时,我想使用R'smessage()warning()函数为我的包用户生成输出。

有时这些消息可能很长。我可以做到这一点(文字只是一个简单的例子):

message("If you got to this point in the code, it means the matrix was empty. Calculation continues but you should consider re-evaluating an earlier step in the process")
Run Code Online (Sandbox Code Playgroud)

太棒了……但是为了风格,我也希望我的代码行少于 80 个字符,这样它们就可以很好地适应窄屏、GitHub 等。然后我可以使用 IDE 代码重排工具轻松地重新格式化我的消息如果它改变。

所以我试试这个:

message("If you got to this point in the code, it means 
the matrix was empty. Calculation continues but you should consider
 re-evaluating an earlier step in the process")
Run Code Online (Sandbox Code Playgroud)

这解决了我的代码标准——它少于 80 个字符行并且可以按预期回流。但这在我的消息输出中保留了空格,我也不想要:

If you got to this point in the code, it means 
the matrix was empty. Calculation continues but you should consider
 re-evaluating an earlier step in the process
Run Code Online (Sandbox Code Playgroud)

所以我发现这个方便的函数调用strwrap()似乎解决了这个问题:

message(strwrap("If you got to this point in the code, it means 
the matrix was empty. Calculation continues but you should consider
 re-evaluating an earlier step in the process"))
Run Code Online (Sandbox Code Playgroud)

输出:

If you got to this point in the code, it means the matrix was empty. 
Calculation continues but you should considerre-evaluating an earlier 
step in the process
Run Code Online (Sandbox Code Playgroud)

看起来不错——但它消除了“考虑”和“重新评估”之间的空间,因为该空间位于换行符处。

另一种选择是在代码中将其分解为多个块:

message("If you got to this point in the code, it means ", 
"the matrix was empty. Calculation continues but you should consider ",
"re-evaluating an earlier step in the process")
Run Code Online (Sandbox Code Playgroud)

这使输出看起来正确,但文本不能再使用 IDE 等轻松回流,因为它不是一个字符串,所以这在开发方面对我不起作用。

那么:如何制作格式良好的消息,让我轻松地跨行编写消息?

我写了这个函数:

.nicemsg = function(...) {
    message(paste(strwrap(...), collapse="\n"))
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法使用内置函数,这样我就不必在我编写的每个 R 包中都包含这个函数?

Ben*_*min 5

使用更多的参数 fromstrwrap使这成为可能

message(strwrap(..., prefix = " ", initial = ""))
Run Code Online (Sandbox Code Playgroud)

您可以通过调整参数的顺序来提高可读性。我不确定这是否更好。

message(strwrap(prefix = " ", initial = "", 
  "If you got to this point in the code, it means 
the matrix was empty. Calculation continues but you should consider
 re-evaluating an earlier step in the process"))
Run Code Online (Sandbox Code Playgroud)

或者,如果您更喜欢包装它

tidymess <- function(..., prefix = " ", initial = ""){
  message(strwrap(..., prefix = prefix, initial = initial))
}
Run Code Online (Sandbox Code Playgroud)

  • 我特别喜欢函数名`tidymess`。这也是我如何描述我的办公室。 (2认同)