这似乎是一个简单的问题,但我找不到答案。我有一个包含调用参数名称的字符向量。在一个函数中,我想发出警告,如果其中一些是错误的,并引用名称。
bad = c("a", "b", "c")
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong"))
给出:
Warning message:
Variables a, b, c are wrong
但我需要:
Warning message:
Variables 'a', 'b', 'c' are wrong
我想在不使用外部包的情况下实现这一目标。
答案 0 :(得分:8)
我们可以使用ASCII撇号\'
warning(paste("Variables", paste0("\'", bad, "\'", collapse = ", "), "are wrong"))
# Warning message:
# Variables 'a', 'b', 'c' are wrong
或sQuote
warning(paste("Variables", paste(sQuote(bad), collapse = ", "), "are wrong"))
# Warning message:
# Variables ‘a’, ‘b’, ‘c’ are wrong
或dQuote
warning(paste("Variables", paste(dQuote(bad), collapse = ", "), "are wrong"))
# Warning message:
# Variables “a”, “b”, “c” are wrong
答案 1 :(得分:4)
您可以使用此方法:
warning("Variables ", paste0("'", bad, "'", collapse = ", "), " are wrong")
# Warning message:
# Variables 'a', 'b', 'c' are wrong
双引号的替代版本:
warning("Variables ", paste0("\"", bad, "\"", collapse = ", "), " are wrong")
# Warning message:
# Variables "a", "b", "c" are wrong
答案 2 :(得分:1)
这是你要找的吗?
bad = c("'a'", "'b'", "'c'")
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong"))
如果您想保存一些打字,可以写一些类似
的内容quotify <- function(x) paste0("'", x, "'")
bad = quotify(c("a", "b", "c"))
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong"))