str_replace_all problem

#1

Hi, I am trying to use str_replace_all but get this error:

In stri_replace_all_regex(string, pattern, fix_replacement(replacement), :
argument is not an atomic vector; coercing

Here's my code:

  str_replace_all(c('17412F45' = "Accent LE",
                    '28402F45' = "Sonata SE",
                    '284H2F4P' = "Sonata SE",
                    '284J2F4P' = "Sonata SEL",
                    '284K2F4P' = "Sonata Sport",
                    '284L2F4P' = "Sonata Limited",
                    '284M2F45' = "Sonata Limited 2.0T",
                    '48412F45' = "Elantra SE"))
0 Likes

#2

You are just passing the pattern argument, but you are missing the string argument, so the function doesn't have nothing to replace.

library(stringr)

text = c("apples and oranges and pears and bananas")

str_replace_all(string = text,
                pattern = c('apples' = "pineapples",
                            'oranges' = "strawberries")
)
#> [1] "pineapples and strawberries and pears and bananas"
0 Likes

#3

The usage of str_replace_all is

str_replace_all(string, pattern, replacement)

You are only providing the string parameter. Can you explain more about what you want to accomplish?

0 Likes

#4

no sorry, this is just a part of my code. let's say I have it like this:

x <- y %>%
str_replace_all(....

unless I still need to use the argument?
And it's a tibble and not a vector if that helps

0 Likes

#5

For a dataframe and with dplyr you need to use it this way

library(dplyr)
library(stringr)

fruits <- data.frame(
    col = c("apples and oranges and pears and bananas", 
            "pineapples and mangos and guavas")
)

fruits %>% 
    mutate(col = str_replace_all(col, pattern = c('apples' = "pineapples",
                                                  'oranges' = "strawberries")))
#>                                                 col
#> 1 pineapples and strawberries and pears and bananas
#> 2              pinepineapples and mangos and guavas
2 Likes

#6

About this, to avoid unnecessary back and forths on future posts, please provide a REPRoducible EXample (reprex)

If you've never heard of a reprex before, you might want to start by reading this FAQ:

0 Likes

closed #7

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.

0 Likes