1

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

4 Answers 4

5

using sprintf

x <- "b"
sprintf('"a" "%s"', x)
# [1] "\"a\" \"b\""
Sign up to request clarification or add additional context in comments.

Comments

2

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\""

1 Comment

In recent versions of R, you could shorten this to x <- "b"; paste('"a"', paste0('"', x, '"'))
2

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

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

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

1 Comment

The collapse = "" is redundant here.
1

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\""

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.