jeudi 11 avril 2019

Collapsing group of strings into one string using an if statement within a for loop in R

I have a dataframe with a column "Food."

dataframe <- data.frame(Color = c("red","red","red","red","red","blue","blue","blue","blue","blue","green","green","green","green","green","orange","orange","orange","orange","orange"), 
Food = c("banana","apple","potato","orange","egg","strawberry","cheese","yogurt","kiwi","butter","kale","sugar","carrot","celery","radish","cereal","milk","blueberry","squash","lemon"), Count = c(2,5,4,8,10,7,5,6,9,11,1,8,5,3,7,9,2,3,6,4))

Every time a fruit appears I want to replace the name of the fruit with "fruit."

I've tried making a vector of the fruit names. Then I go through each row in the dataframe and where the string matches the fruit, I want to replace the fruit name with "fruit."

fruit_list <- c("banana","apple","orange","strawberry","kiwi","blueberry","lemon")

for (r in 1:nrow(dataframe)) {
  for (i in 1:length(fruit_list)){
    if (length(grep(fruit_list[i], dataframe$Food[r])) != 0) { 
      dataframe$Food[r] <- paste("fruit") 
    }
  }
}

How do I use this general format so that dataframe$Food doesn't just end up filled with NA?

Aucun commentaire:

Enregistrer un commentaire