R:str_replace_all函数不将"2010-12-31+10"转换为"2011-01-10"



我有一个这样的字符串:

str1 <- "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2010-12-31+10 less than 2000"

我正在尝试将"2010-12-31+10"转换为"2011-01-10"str1。我尝试了str_replace_all stringr包的方法但我没有得到输出。

> str_replace_all(str1,"2010-12-31+10","2011-01-10")
[1] "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2010-12-31+10 less than 2000"

这是什么原因呢?

str_replace_all 的第二个参数不是字符串,而是正则表达式。所以你必须转义在正则表达式中具有特殊含义的符号,例如+

R> str_replace_all(str1,"2010-12-31\+10","2011-01-10")
[1] "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2011-01-10 less than 2000"

或者您可以使用 stringrfixed 函数使其与你的模式匹配为常规字符串:

R> str_replace_all(str1,fixed("2010-12-31+10"),"2011-01-10")
[1] "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2011-01-10 less than 2000"

相关内容

最新更新