在開發R包時,我想用R
的message()
或warning()
函數爲我的包用戶生成輸出。如何格式化多行R包消息?
有時這些消息可能很長。我能做到這一點(文本只是簡單的例子):
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(...,prefix =「」,initial =「」))'做你需要的嗎? – Benjamin
@Benjamin是的,謝謝。不幸的是它不是比我的功能更簡潔,所以我仍然可能需要包裝它... – nsheff
@Benjamin因爲還沒有任何其他答案,如果你張貼這個答案我會接受它。 – nsheff