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

问题描述 投票:1回答:1

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

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

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

函数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. 
r
1个回答
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的论据,以提供更多的灵活性/控制。)

© www.soinside.com 2019 - 2024. All rights reserved.