rstringrtidy

str_replace in a data frame?


In my R code I'm trying to insert a line break into a few longer string values of one of the columns in my data set. The code runs, but the output is always identical to the original string with no changes occurring. When I pull the column out as a vector and apply the same code, it works completely fine. I'm still new to R and the process of removing a column to apply a function and then re-attaching it to the original data frame seems rather complicated. Is there a successful way I can do this just within the data frame?

library(tidyverse)
library(stringr)

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

Thanks for your help!


Solution

  • It might be useful to look at your original data frame and the output data frame, because your code works perfectly for me on a dummy data frame:

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

    So now when I run your code exactly as-is:

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

    and check dog_descriptions2, I get

    > dog_descriptions2
    >#        breed_primary number_of_legs      breed_primary2
    ># 1   Pit Bull Terrier              4   Pit Bull\nTerrier
    ># 2 Labrador Retriever              4 Labrador\nRetriever
    ># 3      Border Collie              4      Border\nCollie