sparrow sparrow - 5 months ago 21
R Question

Quote names in warnings

This seems like an easy question, but I couldn't find the answer. I have a character vector containing names of arguments of a call. In a function, I would like to give a warning if some of those are wrong, and quote the names.

bad = c("a", "b", "c")
warning(paste("Variables", paste(bad, collapse = ", "), "are wrong"))


which gives:

Warning message:
Variables a, b, c are wrong


but I need:

Warning message:
Variables 'a', 'b', 'c' are wrong


I would like to achieve this without the use of external packages.

Answer Source

We can use ASCII apostrophe \'

warning(paste("Variables", paste0("\'", bad, "\'", collapse = ", "), "are wrong"))

# Warning message:
# Variables 'a', 'b', 'c' are wrong 

Or a single quote bysQuote

warning(paste("Variables", paste(sQuote(bad), collapse = ", "), "are wrong"))

# Warning message:
# Variables ‘a’, ‘b’, ‘c’ are wrong 

Or a double quote bydQuote

warning(paste("Variables", paste(dQuote(bad), collapse = ", "), "are wrong"))

# Warning message:
# Variables “a”, “b”, “c” are wrong