Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 607
Bex Avatar asked Apr 11 '19 16:04

Bex


2 Answers

With dplyr:

  library(dplyr)
    ataframe %>% 
      mutate(Food=as.character(Food),
             Food=ifelse(Food%in%fruit_list,"Fruit",Food))#can change to fruit

Result:

 Color   Food Count
1     red  Fruit     2
2     red  Fruit     5
3     red potato     4
4     red  Fruit     8
5     red    egg    10
6    blue  Fruit     7
7    blue cheese     5
8    blue yogurt     6
9    blue  Fruit     9
10   blue butter    11
11  green   kale     1
12  green  sugar     8
13  green carrot     5
14  green celery     3
15  green radish     7
16 orange cereal     9
17 orange   milk     2
18 orange  Fruit     3
19 orange squash     6
20 orange  Fruit     4
like image 102
NelsonGon Avatar answered Nov 20 '22 01:11

NelsonGon


Only R base:

dataframe$Food <- 
sapply(dataframe$Food,
        function(x,fruit_list) ifelse(x %in% fruit_list, "fruit", as.character(x) ),
        fruit_list = fruit_list ) 
like image 2
Iman Avatar answered Nov 20 '22 02:11

Iman