Search code examples
rif-statementvectorlogiclogical-operators

Using 'IF' operator to check if a given value in a dataframe cell belongs to a 'SET' of values


I have a data.frame with names of animals

x=data.frame(c("lion","tiger","cow","vulture","hyena","leopard","deer","gazzelle"))
colnames(x)=c('animal')

#create sets of animals based on the their diet

carnivore=c("lion","tiger","leopard")
herbivore=c("cow","deer","gazzelle")
omnivore=c("vulture","hyena")

x$diet=NA   ## Add a new column where I want to enter if the animal is one of herbivore, carnivore or omnivore based on the value in x$animal

for (i in 1:(nrow(x))) {
  if (x$animal[i] 'is a subset of' "Omnivore") {
    x$diet[i] = "Omnivore"
  } else if (x$animal[i] 'is a subset of' "Carnivore") {
    x$diet[i] = "Carnivore"
  } else if (x$animal[i] 'is a subset of' "Herbivore") {
    x$diet[i] = "Herbivore"
  }
}





    

I am not quite able to write the code equivalent of 'is a subset of' in R, which I believe must have a simple solution. Any help is much appreciated


Solution

  • Your existing code needs %in% operator:

    for (i in 1:(nrow(x))) {
      if (x$animal[i] %in% omnivore) {
        x$diet[i] = "Omnivore"
      } else if (x$animal[i] %in% carnivore) {
        x$diet[i] = "Carnivore"
      } else if (x$animal[i] %in% herbivore) {
        x$diet[i] = "Herbivore"
      }
    }
    

    I prefer nested ifelse() instead of forloop + if{}else{}:

    x$diet <- ifelse(x$animal %in% carnivore, "Carnivore",
                     ifelse(x$animal %in% herbivore, "Herbivore",
                            ifelse(x$animal %in% omnivore, "Omnivore", "Other")))
    x
    #     animal      diet
    # 1     lion Carnivore
    # 2    tiger Carnivore
    # 3      cow Herbivore
    # 4  vulture  Omnivore
    # 5    hyena  Omnivore
    # 6  leopard Carnivore
    # 7     deer Herbivore
    # 8 gazzelle Herbivore