我正在尝试将一些文本信息转换为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"
字符串的第一部分正是我想要的,所以现在我只需要改变第二部分的内容。 &#34;不是varB == 1&#34;需要改成&#34; varB!= 1&#34;。
有没有人知道如何做到这一点?它甚至可能吗?非常感谢提前!
答案 0 :(得分:3)
这是我使用stringr
的解决方案:
library(stringr)
str_replace_all(exampleTrans, "not (\\w+) =", "\\1 !")
[1] "varA == 1 & varB != 1"
说明:将模式not (word) =
替换为(word) !
,其中word
是不带空格的变量名称。如果您有特定的变量名称,请相应地调整它,包括例如数字或下划线。
答案 1 :(得分:0)
好的,这是我的解决方案:
str_split()
将字符串拆分为两部分。这对于检测具有not
的字符串部分非常有用。 is
不存在时==
替换not
,!=
时not
替换&
。 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 = "&")
折叠结果。 这是我的代码:
{{1}}
希望它有效!