gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:10:29 24 4
gpt4 key购买 nike

在开发 R 包时,我想使用 Rmessage()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"))
}

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

最佳答案

使用来自 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))
}

关于r - 你如何格式化多行 R 包消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45693010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com