search/replace with mutate_if and str_replace_all

Any thoughts on where I'm messing up? Thanks!

I followed the suggestions from 3548/7 and the examples shown there work, but not this attempt:

library(tidyverse)
df <- tibble(col1 = c("^GSPC", "^IXIC", "^DJI"), 
             col2 = c(1, 2, 3))
dplyr::mutate_if(df,
                 is.character,
                 stringr::str_replace_all, 
                 pattern = "^", 
                 replacement = "")
dplyr::mutate_if(df,
                is.character,
                stringr::str_replace_all, 
                pattern = "^GSPC", 
                replacement = "SP500")
# # A tibble: 3 × 2
## col1   col2
# <chr> <dbl>
# 1 ^GSPC     1
# 2 ^IXIC     2
# 3 ^DJI      3

The character ^ is used in regular expressions to designate the beginning of the text. If you want to search for a literal ^, you have to escape it with backslashes. Are the following results what you want?

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
df <- tibble(col1 = c("^GSPC", "^IXIC", "^DJI"), 
             col2 = c(1, 2, 3))
dplyr::mutate_if(df,
                 is.character,
                 stringr::str_replace_all, 
                 pattern = "\\^", 
                 replacement = "")
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <dbl>
#> 1 GSPC      1
#> 2 IXIC      2
#> 3 DJI       3
dplyr::mutate_if(df,
                 is.character,
                 stringr::str_replace_all, 
                 pattern = "\\^GSPC", 
                 replacement = "SP500")
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <dbl>
#> 1 SP500     1
#> 2 ^IXIC     2
#> 3 ^DJI      3

Created on 2022-07-02 by the reprex package (v2.0.1)

1 Like

Thank you so much FJCC!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.