samedi 23 octobre 2021

R: using a switch function with a numeric type value?

I am attempting to apply a switch function to a set of numeric values using documentation from here. I am able to get character values working, but not numerical values. Is there a proper syntax I am missing to get the function to work?:

#original function with numerical values
x_option <- function(x) {
  if (x == 1) {
    "option 1"
  } else if (x == 2) {
    "option 2" 
  } else if (x == 3) {
    "option 3"
  } else {
    stop("Invalid `x` value")
  }
}

#numerical values here make the function break down
x_option <- function(x) {
  switch(x,
         1 = "option 1",
         2 = "option 2",
         3 = "option 3",
         stop("Invalid `x` value")
  )
}

Aucun commentaire:

Enregistrer un commentaire