Ogre Magi
Ogre Magi

Reputation: 1525

Pass string variable into paste R function with escaped double quotes

I need the exact same output from this line of code,

> paste('"a"','"b"')
[1] "\"a\" \"b\""

but I need "b" to be a variable which changes in each iteration, so suppose I have x <-"b", paste('"a"',x) or any other ways I tried failed to give me the output I wanted, which is

> paste('"a"','"b"')
[1] "\"a\" \"b\""

Thanks in advance!

OM

Upvotes: 1

Views: 2230

Answers (4)

Nick Kennedy
Nick Kennedy

Reputation: 12640

One way of doing this with a function would be:

quote_me <- function(...) paste0('"', unlist(list(...)), '"')
x <- "b"
quote_me("a", b)
#[1] "\"a\"" "\"b\""

Upvotes: 1

Andrelrms
Andrelrms

Reputation: 819

There must be a better way to it, but this works:

x<-paste0('"',"b",'"',collapse = "")

paste('"a"',x)
[1] "\"a\" \"b\""

Upvotes: 2

Rorschach
Rorschach

Reputation: 32416

using sprintf

x <- "b"
sprintf('"a" "%s"', x)
# [1] "\"a\" \"b\""

Upvotes: 5

HasaniH
HasaniH

Reputation: 8392

If you are using a variable then you have to manually surround it with double quotes. You can use an extra call to paste to do that

> x <- "b"
> paste('"a"', paste('"', x, '"', sep=''))
[1] "\"a\" \"b\""

Upvotes: 2

Related Questions