Search code examples
rswitch-statementsapply

Why are R's sapply and switch functions treating a character value like a function?


I am trying to use sapply and switch to apply descriptive names to data. I've used this methodology many times without issue, but for (only one!) column in my most recent project it is throwing an error. My best guess is that even though the value is saved as a character string, that value would otherwise be a reserved word in R. I've created a reproduceable example below.

The actual values in my project are not gender related and could have many possible options. Can someone please tell me how to make this work with sapply/switch to avoid many nested ifelse statements in my code?

# create test data
testdta <- as.data.frame(cbind(userid = c("1", "2", "3", "4"), gender = c("F", "M", "F", "M")))

# sapply/switch works with strings that are not reserved words
testdta$uiddescription <- sapply(testdta$userid, switch, "1" = "1 - first", "2" = "2 - second", "3+ - third or beyond")
testdta

# sapply/switch won't work when trying to interpret gender (possibly because F is reserved?)
testdta$gdescription <- sapply(testdta$gender, switch, "F" = "F - female", "M" = "M - male")

The error I am receiving is "Error in get(as.character(FUN), mode = "function", envir = envir) : object 'F - female' of mode 'function' was not found."


Solution

  • It's happening because of partial argument matching in sapply. It reads the "F" = as the FUN argument in sapply. If you are explicit and do FUN = switch it will work.