ExploreR
ExploreR

Reputation: 343

How to embed a character string (stored in a variable) in quotation marks using R?

How to use escape characters to embed a character string, stored in a variable, in single quotation marks?

I already gave it some try-and-error-approaches, but failed.

To illustrate what I want to achieve here an example:

from:
"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"

to:
'"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"'

Thanks a lot in advance, ExploreR

proj4string(spatial_data)
[1] "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
# this is the character string i want to embed into quotation marks

input_crs <- paste(\'input_crs\')
Error: '\,' is an unrecognized escape in character string starting ""\,"

Upvotes: 0

Views: 855

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

One option, adding single quotes around the input using paste:

from <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
to <- paste0("'", from, "'")

Or, if you want your input to be surrounded by literal double quotes, then use:

to <- paste0("\"", from, "\"")

Or we could use sub:

to <- sub("^(.*)$", "'\\1'", from)

Upvotes: 1

Jaccar
Jaccar

Reputation: 1844

You would still need to surround by quotation marks, but can use double quotes rather than single, so either of the following work.

> input_crs <- '\'input_crs\''
> input_crs
[1] "'input_crs'"

> input_crs_2 <- "input_crs'"
> input_crs_2
[1] "input_crs'"

You don't need to use paste0() for that because things aren't being combined. If you were using a variable that had stored something, you would use paste0():

> input <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
> paste0("'", input, "'")
[1] "'+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0'"

Info on quotes here says:

Single and double quotes delimit character constants. They can be used interchangeably but double quotes are preferred (and character constants are printed using double quotes), so single quotes are normally only used to delimit character constants containing double quotes.

Backslash is used to start an escape sequence inside character constants. Escaping a character not in the following table is an error.

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

Upvotes: 0

Related Questions