2014-06-25 17 views
2

我想将一些文本信息翻译成R脚本。为此,我需要替换和重新排列部分字符串。如何重新排序和替换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”。

有没有人有关于如何做到这一点的想法?它甚至有可能吗?提前谢谢了!

回答

3

下面是使用stringr我的解决方案:

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

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

+0

感谢您的快速响应! – rdatasculptor

+0

欢迎您!有趣的问题。 – tonytonov

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 = "&") 

希望工程!