Say I have the following dataframe (the real one is 10 labelx columns):
id <- c(1,2,3,4,5,6,7,8)
label1 <- c("apple","shoe","banana","hat","dog","radio","tree","pie")
label2 <- c("apple","sneaker","fruit","beanie","pet","ipod","doug fir","pie")
df <- data.frame(id,label1,label2)
And I would like to replace all items in the label columns with a word that categorizes it.
food <- c("apple","banana","pie","fruit")
clothing <- c("shoe","hat","beanie")
entertainment <- c("radio","ipod","mp3 player","phone")
forest <- c("tree","doug fir","redwood","forest")
I've tried something like the following:
column_list <- c("label1","label2")
new_df <- df
for(i in 1:2) {
new_df <- new_df %>%
mutate(parse(text=column_list[i-1]) = replace(parse(text=column_list[i-1]),
(parse(text=column_list[i-1]) %in% food),
"food"))
}
I don't have to do it this way, easier is fine too. Tidyverse preferred. How do I replace multiple values among multiple columns in R dataframe?