如何在警告消息中的元素之间添加分隔符?

时间:2017-12-18 03:52:28

标签: r

这个问题很可能已经多次回答,但即使经过大力搜索,我似乎也找不到答案......

我想使用字符向量创建警告消息。矢量中的元素应以“,”分隔,不应重复。像这样:

  

警告消息:条目这也是,也可能是应该检查的。

函数warning将消息传递给cat函数,这使我很难理解如何使用cat内的warning

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. 

1 个答案:

答案 0 :(得分: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.

(我添加了pastewarning的参数,以提供更多的灵活性/控制。)