• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

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

r 来源:Mikko 7次浏览

这个问题最有可能已经回答了很多次,但我似乎没有找到答案,即使经过大力的搜索…如何在警告消息中的元素之间添加分隔符?

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

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

功能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. 


===========解决方案如下:

如果你这样做一次,就可以只是使用类似:

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提供一些更多的灵活性/控制。)


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)