Вопрос

I have a string like this:

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"

I am trying to convert "2010-12-31+10" to "2011-01-10" in str1. I tried str_replace_all method of stringr package But i didnt get the output.

> 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"

What is the reason for that?

Это было полезно?

Решение

The second argument of str_replace_all is not a character string but a regular expression. So you have to escape the symbols such as + that have a special meaning in regexps :

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"

Or you can use the fixed function of stringr to make it match your pattern as a regular string :

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"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top