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.