如何`chartr`一个“-"(或转义范围)? [英] How to `chartr` a "-" (or escaping ranges)?

查看:38
本文介绍了如何`chartr`一个“-"(或转义范围)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In R one can use chartr to change characters from one to another, eg.:

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

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

Pattern could be ranges (e.g. chartr("a-hwo","0-9","Stackoverflow")), but length need to match.

但是如何替换"-"?

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

我找到了一种解决方法 - 将字符放在开头或结尾:

I found one workaround - putting char at the beginning or the end:

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

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

But I using this to randomly replace chars so in my pattern "-" could be anywhere:

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

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

Is there way to turn off ranges / escape range character / etc?

推荐答案

- 的 unicode 代码点低于 a,因此报错

The unicode code point for - is lower than a, thus the error stating

递减范围规范 ('b--')

decreasing range specification ('b--')

所以如果使用范围,你需要把它放在a之前

So you need to place it before a if using a range

没有范围:

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

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

You can subsequently use - to denote a range (keeping the lengths matching in old and new

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

这篇关于如何`chartr`一个“-"(或转义范围)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆