3

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.

3 Answers 3

8

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
2
  • This is neat, but I wouldn't use left/right quotes in a warning. However, I wouldn't add quotes at all.
    – Roland
    Aug 17, 2017 at 6:21
  • @Roland Thank you, edited my answer, however, the usage depends on the user.
    – Agaz Wani
    Aug 17, 2017 at 6:38
4

You can use this approach:

warning("Variables ", paste0("'", bad, "'", collapse = ", "), " are wrong")
# Warning message:
# Variables 'a', 'b', 'c' are wrong 

Alternative version for double quotation marks:

warning("Variables ", paste0("\"", bad, "\"", collapse = ", "), " are wrong")
# Warning message:
# Variables "a", "b", "c" are wrong 
1

Is this what you're looking for?

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

if you want to save some typing you can write something like

quotify <- function(x) paste0("'", x, "'")

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.