如何格式化多行R包邮件?

时间:2017-08-15 12:39:27

标签: r string format message

在开发R包时,我想使用R的{​​{1}}或message()函数为我的包用户生成输出。

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

warning()

很棒...但是对于样式,我也希望我的代码行少于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个字符行并且可以按预期重排。但是这会在我的消息输出中粘贴空格,我也不想要:

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")

所以我发现这个名为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

这使得输出看起来正确,但是文本不能再用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")

使用内置是否有更好的方法,所以我不必在我写的每个R包中都包含这个函数?

2 个答案:

答案 0 :(得分:2)

使用来自strwrap的更多参数可以实现

message(strwrap(..., prefix = " ", initial = ""))

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

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"))

或者,如果你喜欢包装它

tidymess <- function(..., prefix = " ", initial = ""){
  message(strwrap(..., prefix = prefix, initial = initial))
}

答案 1 :(得分:-1)

您可以通过在字符串中添加\n来强制换行。

message("If you got to this point in the code,\nit means the matrix was empty.\nCalculation continues but you should consider re-evaluating\nan 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 consider re-evaluating
# an earlier step in the process