简体   繁体   中英

Deparse and (un)escape quotes

I have the following list:

lst <- list(a = "", b = 2)

and want to deparse it to text:

> deparse(lst, width.cutoff = 100)
[1] "structure(list(a = \"\", b = \"\"), .Names = c(\"a\", \"b\"))"

and then i want to run the text as code (in the console):

> structure(list(a = \"\", b = \"\"), .Names = c(\"a\", \"b\"))
Error: unexpected input in "structure(list(a = \"

I know it Fails, because of the backslashes: (without them it works obviously).

structure(list(a = "", b = ""), .Names = c("a", "b"))

Question:

How can i avoid creating the backslashes?

What i tried:

I went through the given Parameter. Backtick seemed like a candidate, but didnt work. Using gsub to replace them is a candidate, but way to dirty i guess,..

Tools:

R 3.4.3 Rstudio 1.1.447

Update: Upgrade to 3.6 - similar issue.

> lst <- list(a = "", b = 2)
> deparse(lst, width.cutoff = 100)
[1] "list(a = \"\", b = 2)"
> list(a = \"\", b = 2)
Error: unexpected input in "list(a = \"

There are couple of ways to modify the behavior. One way is to print with cat on the console, copy and paste that (used R 3.6.0 )

out <- deparse(lst, width.cutoff = 100)
cat(out, sep="\n")
#list(a = "", b = 2)
list(a = "", b = 2)
#$a
#[1] ""

#$b
#[1] 2

Note that cat also have a file argument if the output needs to be written to some file and used it later


Or use gsub to remove the " and replace with single quotes ( ' )

out1 <- gsub('"', "'", out)
out1
#[1] "list(a = '', b = 2)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM