ECII
ECII

Reputation: 10629

How to print variables inside quotes in message()

I have the following variables:

min.v<-5
max.v<-10

and i want to message the following

Test this. You entered "5 10" 

Is this possible to print this with message() or paste(), since both functions regard quotes as strings. The variables in the message should be inside double quotes

I have tried message(as.character(paste(min.v, " ",max.v))) but the double quotes are ignored.

This question is probably the exact opposite of this Solve the Double qoutes within double quotes issue in R

Upvotes: 0

Views: 13789

Answers (3)

ssokolen
ssokolen

Reputation: 478

Although sprintf can get quite complex, I find the code is generally neater than most other options. Essentially, you have a message that you want to format where you want to insert variable values -- this is what sprintf is for:

min.v <- 5
max.v <- 10
msg <- 'Test this. You entered "%i %i"\n'
str <- sprintf(msg, min.v, max.v) #generates string
cat(str) #to output
# or message(str)

The %i are placeholders that expect integer values, see ?sprintf for more details. Although this solution still relies on surrounding double quotes with single quotes, you get much more readable code than when using paste or cat directly.

Upvotes: 0

Andrie
Andrie

Reputation: 179558

You have two three options of doing this

Option 1: Escape the quotes. To do this, you have to use \".

cat("You entered ", "\"", min.v, " ", max.v,"\"", sep="")
You entered "5 10"

Option 2: Embed your double quotes in single quotes:

cat("You entered ", '"', min.v, " ", max.v,'"', sep="")
You entered "5 10"

Edit: with acknowledgement to @baptiste, in an effort to make this answer comprehensive

Option3: Use the function dQuote():

options(useFancyQuotes=FALSE)
cat("You entered ", dQuote(paste(min.v, max.v)), sep="")
You entered "5 10"

Upvotes: 8

baptiste
baptiste

Reputation: 77116

x = 5; y = "indeed"
message("you entered ", dQuote(x))
message("you entered ", dQuote(paste(x, y)))

Upvotes: 4

Related Questions