代码之家  ›  专栏  ›  技术社区  ›  nsheff

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

  •  5
  • nsheff  · 技术社区  · 7 年前

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

    2 回复  |  直到 7 年前
        1
  •  7
  •   Benjamin    7 年前

    使用来自 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))
    }
    
        2
  •  -3
  •   Andrew Brēza    7 年前

    \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