How do I replace a suffix with a prefix across a dataframe in R?

Viewed 35

I have a data frame like the following in R:

df <- data.frame(apple = c("apple", "apple", "applebad", "apple", "apple"),
                orange = c("orangebad", "orangebad", "orange", "orange", "orange"),
                pear = c("pear", "pear", "pear", "pearbad", "pear"))    

However from this data frame I would like to change the suffix of 'bad' to a prefix of rotten so I get a data frame like this:

df_new <- data.frame(apple = c("apple", "apple", "rottenapple", "apple", "apple"),
                orange = c("rottenorange", "rottenorange", "orange", "orange", "orange"),
                pear = c("pear", "pear", "pear", "rottenpear", "pear")) 

So I know that I can do it column by column with str_replace (from stringr) or gsub like so:

df$apple <- gsub("applebad", paste0("rottenapple"), df$apple)
df$apple <- str_replace(df$apple, "applebad", "rottenapple")

but I'm not sure how to do it so that I can iterate over the data frame without having to state "rottenapple", "rottenpear", as my real dataset has 100s of columns. I have tried the following but that does not work:

item <- c("apple", "orange", "pear")

df[,1] <- str_replace(df[,1], "bad", paste0("rotten", item[1]))

Any help most appreciated.

1 Answers

We could capture rest of the characters as a group ((.*)) followed by 'bad' and replace with the rotten substring and the backreference (\\1) of the captured group

library(dplyr)
library(stringr)
df <- df %>% 
    mutate(across(everything(),  ~str_replace(.x, "(.*)bad", "rotten\\1")))

-checking

all.equal(df, df_new)
[1] TRUE

Or using base R

 df[] <- lapply(df, gsub, pattern = "(.*)bad", replacement = "rotten\\1")
> df
        apple       orange       pear
1       apple rottenorange       pear
2       apple rottenorange       pear
3 rottenapple       orange       pear
4       apple       orange rottenpear
5       apple       orange       pear
Related