1

How to print " around my text using sprintf in R?

Example:

Name<-"X"
sprintf({"%s"},Name)

which the output is:

[1] "X"

But I need

[1] ""X""
Ester Silva
  • 670
  • 6
  • 24

2 Answers2

2

I think what you want is shQuote You can do

shQuote(Name)
# [1] "\"X\""

Note that R needs to escape the inner quotes in the console. It will not print out something that looks like ""X"". But if you cat the values the slashes aren't there

cat(shQuote(Name))
# "X"
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Thanks but No @MrFlick, I want to use the `sprintf` since I need to assign the output of `sprintf` to a variable. So I guess `cat` cannot be useful. Also, `shQuote(Name)` which is not correct. – Ester Silva Jan 05 '18 at 15:57
  • @EsterSilva That doesn't make sense. you can assign the output of `shQuote` just like you can `sprintf`. What exactly are you trying to do with this value? Can you provide some sort of [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that demonstrates why you need to quote this string value so that possible solutions other than what you are expecting can be tested and shown to produce the desired result. – MrFlick Jan 05 '18 at 16:01
0

I'm not sure if another option will help you. But you can consider it:

The option could be:

Name<-"X"
#> sprintf("'%s'",Name)
#[1] "'X'"
MKR
  • 19,739
  • 4
  • 23
  • 33