Toolbox
Toolbox

Reputation: 2473

R - Construct a string with double quotations

I basically need the outcome (string) to have double quotations, thus need of escape character. Preferabily solving with R base, without extra R packages.

I have tried with squote, shQuote and noquote. They just manipulate the quotations, not the escape character.

My list:

power <- "test"

myList <- list (
                "power" = power)

I subset the content using:

myList
myList$power

Expected outcome (a string with following content):

" \"power\": \"test\" "

Upvotes: 0

Views: 219

Answers (3)

s_baldur
s_baldur

Reputation: 33498

Using package glue:

library(glue)
glue(' "{names(myList)}": "{myList}" ')
 "power": "test" 

Upvotes: 3

markus
markus

Reputation: 26343

Another option using shQuote

paste(shQuote(names(myList), type = "cmd"),
      shQuote(unlist(myList), type = "cmd"),
      sep = ": ")
# [1] "\"power\": \"test\""

Upvotes: 1

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Not sure to get your expectation. Is it what you want?

myList <- list (
  "power" = "test"
)
stringr::str_remove_all(
  as.character(jsonlite::toJSON(myList, auto_unbox = TRUE)), 
  "[\\{|\\}]")
# [1] "\"power\":\"test\""

If you want some spaces:

x <- stringr::str_remove_all(
  as.character(jsonlite::toJSON(myList, auto_unbox = TRUE)), 
  "[\\{|\\}]")
paste0(" ", x, " ")

Upvotes: 0

Related Questions