首页 > 解决方案 > 如何使用 R 将字符串(存储在变量中)嵌入引号中?

问题描述

如何使用转义字符将存储在变量中的字符串嵌入单引号中?

我已经给了它一些尝试和错误的方法,但失败了。

为了说明我想在这里实现的一个例子:

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

非常感谢,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 ""\,"

标签: rstringcharacterquotes

解决方案


一种选择,使用在输入周围添加单引号paste

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

或者,如果您希望输入用文字双引号括起来,请使用:

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

或者我们可以使用sub

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

推荐阅读