str_replace_all problem

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

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"

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?

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

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

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:

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.