连接粘贴和粘贴中的特殊字符串

时间:2019-05-28 07:57:49

标签: r string escaping paste

我想知道如何在paste0中连接特殊字符串,例如 \ item

paste0("\item", "b")


paste0("a", "b")
#> [1] "ab"
  paste0("a", "\b")
#> [1] "a\b"
paste0("\item", "\b")
#> Error: '\i' is an unrecognized escape in character string starting ""\i"

已编辑

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
  head(airquality) %>%
  mutate(Ozone1 = cat(paste0("\\item{", Ozone)))
#> \item{41 \item{36 \item{12 \item{18 \item{NA \item{28
#>   Ozone Solar.R Wind Temp Month Day
#> 1    41     190  7.4   67     5   1
#> 2    36     118  8.0   72     5   2
#> 3    12     149 12.6   74     5   3
#> 4    18     313 11.5   62     5   4
#> 5    NA      NA 14.3   56     5   5
#> 6    28      NA 14.9   66     5   6

1 个答案:

答案 0 :(得分:3)

如错误所述,您需要转义反斜杠。为了用一个反斜杠打印它,您需要使用cat。否则,它将被解释为转义。因此,您将无法按原样添加它。例如,

library(dplyr)
iris %>% mutate(new = paste0("\\item", "b")) #both backslashes are printed

我们不能在cat中使用mutate。反斜杠被转义。要定义单个反斜杠,您需要在字符串中使用双反斜杠。

查找更多信息here