2017-12-18 131 views
1

這個問題最有可能已經回答了很多次,但我似乎沒有找到答案,即使經過大力的搜索...如何在警告消息中的元素之間添加分隔符?

我想創建一個警告消息使用字符向量。向量中的元素應該用「,」分開,不應重複。像這樣:

警告消息:條目這,這也是,也應該檢查。

功能warning將消息傳遞到cat功能,這使得我很難明白,我應該如何使用catwarning

entries2check <-c("This", "that", "this too", "probably also that") 

cat("Entries", entries2check, "should be checked.", sep = ", ") # works 
# Entries, This, that, this too, probably also that, should be checked. 

paste("Entries", entries2check, "should be checked.", collapse = ", ") # repeated 
# [1] "Entries This should be checked., Entries that should be checked., Entries this too should be checked., Entries probably also that should be checked." 

# no separator 
warning("Entries ", entries2check, "should be checked.") 
# Warning message: 
# Entries Thisthatthis tooprobably also thatshould be checked. 

# cat comes before "Warning message:" 
warning(cat("Entries", entries2check, "should be checked.", sep = ", ")) 
# Entries, This, that, this too, probably also that, should be checked.Warning message: 

# correct place, but repeated 
warning(paste("Entries", entries2check, "should be checked.", sep = ", ")) 
# Warning message: 
# Entries, This, should be checked.Entries, that, should be checked.Entries, this too, should be checked.Entries, probably also that, should be checked. 
+3

'警告( 「條目」,糊劑(entries2check,塌陷=」, 「)」,應「)' – r2evans

+1

'toString'對於這一點非常理想,因爲它基本上是'paste(entries2check,collapse =」,「)':'warning(」Entries「,toString(entries2check),」should be checked。「)''。 – A5C1D2H2I1M1N2O1R2T1

回答

4

如果你這樣做一次,就可以只是使用類似:

warning("Entries ", paste(entries2check, collapse=", "), " should be checked.") 

如果你想正式了一點,你可以這樣做:

mywarn <- function(..., sep = " ", collapse = ", ", 
        call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, domain = NULL) { 
    warning(
    paste(sapply(list(...), paste, collapse = collapse), 
      sep = sep), 
    call. = call., immediate. = immediate., noBreaks. = noBreaks., domain = domain 
) 
} 

mywarn("Entries ", entries2check, " should be checked.") 
# Warning in mywarn("Entries ", entries2check, " should be checked.") : 
# Entries This, that, this too, probably also that should be checked. 

mywarn("Entries ", entries2check, " should be checked.", call. = FALSE) 
# Warning: Entries This, that, this too, probably also that should be checked. 

(I加入的參數的pastewarning提供一些更多的靈活性/控制。)

相關問題