R
的
message()
或
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")
太棒了但对于风格,我也希望
代码行少于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"))
}