【问题标题】:parenthesis in make.unique in RR中的make.unique中的括号
【发布时间】:2020-07-27 18:24:11
【问题描述】:

在 R 中使用 make.unique 函数将通过附加 . 和来自 1 的索引来生成唯一变量,例如:

make.unique(c("a1","a1","a1"))
[1] "a1"   "a1.1" "a1.2" 

我正在寻找一个在索引周围加上括号的函数,例如:

make.unique.NEW(c("a1","a1","a1"))
[1] "a1"   "a1(1)" "a1(2)" 

【问题讨论】:

    标签: r unique gsub strsplit


    【解决方案1】:

    使用sub 将括号括在数字周围并删除点:

    sub(r"{\.(\d+)$}", r"{(\1)}", make.unique(c("a","a","a", "a1", "a1")))
    ## [1] "a"     "a(1)"  "a(2)"  "a1"    "a1(1)"
    

    以上要求 R 4.0.0 或更高版本。如果您有早期版本的 R,请使用它(它也适用于 R 4.0.0 及更高版本,但涉及双反斜杠)。

    sub("\\.(\\d+)$", "(\\1)", make.unique(c("a","a","a", "a1", "a1")))
    

    【讨论】:

    • 感谢您的回复,但是如果我的名字中有一个数字,比如我发布的编辑版本
    • @Onyambu,不:sub(".(\\d+)$", "\\(\\1)", make.unique(c("a1","a1","a1"))) [1] "(1)" "a1(1)" "a1(2)"
    • 查看修订版。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    相关资源
    最近更新 更多