jpm
jpm

Reputation: 11

str_replace using arguments from another data frame

This is closely related to my question: str_replace in a data frame?

So I want to solve this problem:

dog_descriptions <- data.frame(breed_primary = c("Pit Bull Terrier",
                                                 "Labrador Retriever",
                                                 "Border Collie"),
                               number_of_legs = rep(4, 3))

dog_descriptions2 <-
  dog_descriptions %>% 
  mutate(breed_primary2 = str_replace_all(breed_primary, c("Pit Bull Terrier" = "Pit Bull\nTerrier", "Labrador Retriever" = "Labrador\nRetriever", "Border Collie" = "Border\nCollie")))

But not using a long text string, but rather the data.frame replacement_input:

Is there any possibility in R to use an object (e.g. the data frame named replacement_input) for the replacement of a complex text string.

replacement_input <- data.frame(replace = c("Pit Bull Terrier", 
                                            "Labrador Retriever", 
                                            "Border Collie", 
                                            "Fourth Entry"), 
                                replace_with = c("Pit Bull\nTerrier", 
                                                 "Labrador\nRetriever", 
                                                 "Border\nCollie", 
                                                 "Replace 4th"))

Conversion to this format should help:

    c("Pit Bull Terrier" = "Pit Bull\nTerrier", "Labrador Retriever" = "Labrador\nRetriever", "Border Collie" = "Border\nCollie"))

I did not success with combination of paste0 and stringr::str_c to create the "replacment vector"

Maybe it is also the wrong approach.

Upvotes: 1

Views: 46

Answers (1)

Mark
Mark

Reputation: 12528

From the documentation:

The replacement value [is] usually a single string, but it can be a vector the same length as string or pattern. In other words, pass the patterns as one vector, and the replacements as another, and it all works.

In practice:

dog_descriptions %>%
      mutate(breed_primary = str_replace_all(breed_primary, 
                                             setNames(replacement_input$replace_with, 
                                                      replacement_input$replace)))

# you could also do:
dog_descriptions %>%
      mutate(breed_primary = ifelse(breed_primary %in% replacement_input$replace, 
                                    replacement_input$replace_with, 
                                    breed_primary))

Upvotes: 0

Related Questions