如何`chartr`一个“ - ”(或逃避范围)?

时间:2017-02-02 22:07:06

标签: r string replace

在R中,可以使用chartr将字符从一个更改为另一个,例如:

chartr("aor","u ^","Stackoverflow")
[1] "Stuck ve^fl w"

模式可以是范围(例如chartr("a-hwo","0-9","Stackoverflow")),但长度需要匹配。

但如何替换"-"

> chartr("ab-;","1234","aaa bbb ccc --- ;")
Error in chartr("ab-;", "1234", "aaa bbb ccc --- ;") : 
  decreasing range specification ('b-;')

> chartr(";-ab","4312","aaa bbb ccc --- ;")
Error in chartr(";-ab", "4312", "aaa bbb ccc --- ;") : 
  'old' is longer than 'new'

> chartr("ab\-;","1234","aaa bbb ccc --- ;")
Error: '\-' is an unrecognized escape in character string starting ""ab\-"

> chartr("ab--;","1234","aaa bbb ccc --- ;")
Error in chartr("ab--;", "1234", "aaa bbb ccc --- ;") : 
  decreasing range specification ('b--')

我找到了一个解决方法 - 在开头或结尾放置char:

> chartr("ab;-","1243","aaa bbb ccc --- ;")
[1] "111 222 ccc 333 4"

但我使用它来随机替换字符,所以在我的模式中"-"可以是任何地方:

chartr(
    old = "-!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~ "
    ,new = "-!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~ " %>% strsplit("") %>% .[[1]] %>% sample %>% paste(collapse="")
    , x = "x@&*#--s"
) # this randomly is ok or throw error (about length or decreasing range)

有没有办法关闭范围/转义范围字符/等?

2 个答案:

答案 0 :(得分:1)

-的unicode代码点低于a,因此错误说明

  

减少范围规格('b - ')

因此,如果使用范围

,则需要将其放在a之前

没有范围:

chartr("-;ab","1234","aaa bbb ccc --- ;")
# [1] "333 444 ccc 111 2"

您随后可以使用-来表示范围(保持长度与新旧匹配

`chartr("-a-c;","12b34","aaa bbb ccc --- ;")
# [1] "222 bbb 333 111 4"

答案 1 :(得分:0)

如果您将每个值都设置为一个从其自身扩展到其自身的范围,则可以执行以下操作:

old <- ";-ab"
new <- "4312"

splcomb <- function(x) gsub("(.)", "\\1-\\1", x)

splcomb(old)
#[1] ";-;---a-ab-b"

chartr(splcomb(old), splcomb(new), "aaa bbb ccc --- ;")
#[1] "111 222 ccc 333 4"