mardi 17 décembre 2019

Vectorizing multiple if statements in a function

I'm trying to create a function that receives a word and returns a number based in which group that word belongs to, I've created the following function, which only works with single inputs:

get_humor <- function(x) {

  feeling <- str_to_lower(x)

  if (x %in% group5) return(5)
  if (x %in% group4) return(4)
  if (x %in% group3) return(3)
  if (x %in% group2) return(2)
  if (x %in% group1) return(1)


}

I know that I can use nested ifelses, like this:

ifelse(x %in% nv5, 5, 
         ifelse(x %in% nv4, 4,
                ifelse(x %in% nv3, 3,
                       ifelse(x %in% nv2, 2, 1))))

But there is a way to make a vectorized version of this function without using other auxiliary functions, like lapply() or Vectorize()?

Aucun commentaire:

Enregistrer un commentaire