在开发一个R包时,我想使用R的message()或warning()函数为我的软件包用户生成输出。有时这些消息可能很长。我可以这样做(文本只是简单的示例):
这解决了我的代码要求——每行字符少于80个,且可以如预期般重新格式化。但是这会将空格粘在我的消息输出中,这也不是我想要的:
这使输出看起来正确,但是文本不再能够轻松地与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")
很不错...但是为了风格,我也希望我的代码行少于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")
这解决了我的代码要求——每行字符少于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
我发现了一个非常方便的函数叫做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"))
输出:
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
看起来很不错 - 但它消除了“考虑”和“重新评估”之间的空格,因为这个空格位于换行符处。
另一种选择是在代码中将它分成几个部分:
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")
这使输出看起来正确,但是文本不再能够轻松地与IDE等重新流动,因为它不是一个字符串,所以在开发方面对我来说这不起作用。
那么:如何制作一个漂亮格式的消息,让我可以轻松地在多行上编写消息?
我已经编写了这个函数:
.nicemsg = function(...) {
message(paste(strwrap(...), collapse="\n"))
}
有没有更好的方法可以使用内置函数,这样我就不必在编写每个R包时都包含此函数?
message(strwrap(..., prefix = " ", initial = ""))
这个函数是否满足你的需求? - Benjamin