2017-08-15 41 views
-1

在開發R包時,我想用Rmessage()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包我寫這篇文章的功能更好的辦法?

+2

呢'消息(strwrap(...,prefix =「」,initial =「」))'做你需要的嗎? – Benjamin

+0

@Benjamin是的,謝謝。不幸的是它不是比我的功能更簡潔,所以我仍然可能需要包裝它... – nsheff

+0

@Benjamin因爲還沒有任何其他答案,如果你張貼這個答案我會接受它。 – nsheff

回答

1

使用一對夫婦更多的參數從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

我特別喜歡函數名稱'tidymess'。這也是我如何描述我的辦公室。 – nsheff

-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 
+0

這既不能解決IDE迴流問題,也不能解決80個字符的限制。請重新閱讀這個問題。 – nsheff

+0

在什麼條件下你想要代碼重排? –

+0

恩,在所有情況下?是的;這仍然像我的第一個例子那樣延伸得太遠了。這一點似乎不清楚:代碼需要包裝在80個字符。您的建議不會將代碼封裝在80個字符處(允許IDE重新排列代碼)。 – nsheff