【问题标题】:how to both reorder and substitute parts of a string in r?如何在 r 中重新排序和替换字符串的一部分?
【发布时间】:2014-06-25 10:32:38
【问题描述】:

我正在尝试将一些文本信息翻译成 R 脚本。为此,我需要替换和重新排序部分字符串。

example <- "varA is 1 and not varB is 1"

这就是我想要的结果(R 脚本的一部分):

exampleTrans <- "varA == 1 & varB != 1"

这是我现在能做的:

exampleTrans <- gsub(" is "," == ", example)
exampleTrans <- gsub(" and ", " & ", exampleTrans)
print(exampleTrans)
[1] "varA == 1 & not varB == 1"

字符串的第一部分正是我想要的,所以现在我只需要更改第二部分的内容。 “not varB == 1”需要改为“varB != 1”。

有没有人知道如何做到这一点?甚至可能吗?非常感谢!

【问题讨论】:

    标签: regex r gsub


    【解决方案1】:

    这是我使用 stringr 的解决方案:

    library(stringr)
    str_replace_all(exampleTrans, "not (\\w+) =", "\\1 !")
    [1] "varA == 1 & varB != 1"
    

    说明:将模式not (word) = 替换为(word) !,其中word 是不带空格的变量名。如果您有特定的变量名称,请相应地调整它,例如数字或下划线。

    【讨论】:

    • 感谢您的快速回复!
    【解决方案2】:

    好的,这是我的解决方案:

    • 首先您需要使用str_split() 将字符串分成两部分。这对于检测具有not 的字符串部分很有用。
    • 然后当not 不存在时用== 替换is,当not 存在时用!= 替换。
    • 然后您可以使用&amp; 折叠结果。

    这是我的代码:

    library("stringr")
    example <- "varA is 1 and not varB is 1"
    out  <- str_split(example, "and")[[1]] 
    ifelse(grepl(pattern = "not", x = out), sub(pattern = "([[:alpha:]]+) is ([[:digit:]]+)", replacement = "\\1 != \\2", x = out), 
        sub(pattern = "([[:alpha:]]+) is ([[:digit:]]+)", replacement = "\\1 == \\2", x = out)
       )
    paste(out, collapse = "&")
    

    希望它有效!

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 2013-06-26
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2021-03-01
      • 2011-04-02
      • 2018-12-18
      • 1970-01-01
      相关资源
      最近更新 更多