switch() accepts as it's first argument
"EXPR an expression evaluating to a number or a character string."
however, can it be coerced to working with a logical? If so, am I doing something else wrong in this code?
I have a column containing logical values in a data frame, and I want to write a new column containing values from the existing data in the data frame based on the logical parameters:
exampleCurrent <- data.frame(value = c(5.5, 4.5, 4, 2.9, 2),
off = as.logical(c("F", "F", "T", "T", "F")),
extremeValue = as.logical(c("F", "F", "F", "F", "T")),
eclMinWork = c(5, 5.3, 5, 4.7, 3),
eclMinOff = c(4, 3.2, 3, 4, 3))
I would like to get to this:
exampleWanted <- data.frame(value = c(5.5, 4.5, 4, 2.9, 2),
off = as.logical(c("F", "F", "T", "T", "F")),
extremeValue = as.logical(c("F", "F", "F", "F", "T")),
eclMinWork = c(5, 5.3, 5, 4.7, 4),
eclMinOff = c(4, 3.2, 3, 4, 3),
output = c(5, 4.5, 3, 2.9, 3))
The rules for selecting a number are:
- Check
off. Ifoffis FALSE, select from eithervalueoreclMinWork. Ifoffis TRUE, select from eithervalueoreclMinOff - Check
extremeValue. IfextreneValue= FALSE, select the smaller ofvalueand the field in step 1. IfextremeValue= TRUE, select the value from the field in step 1.
I have successfully written an ifelse() that performs, though I am wondering if I can use switch instead.
exampleGenerated <- cbind(exampleCurrent, bestCase =
switch(exampleCurrent$off,
FALSE = ifelse(exampleCurrent$value<exampleCurrent$eclMinWork,exampleCurrent$value, exampleCurrent$eclMinWork),
TRUE = ifelse(exampleCurrent$value<exampleCurrent$eclMinOff,exampleCurrent$value, exampleCurrent$eclMinOff)))
The above throws an error, I am assuming as FALSE is not a character, and is not (on the face of it) a numeric or character:
Error: unexpected '=' in: switch(exampleCurrent$off, FALSE ="
However, my attempts at wrapping as.numeric and as.character around the variables have also failed. Is there a way to do it, or am I missing a fundamental mistake in my code?
ifelsestatement withinswitch- David Arenburgifelse()with a straight numerical value, it still doesn't work :( - DaveRGPoff, and then "" on false and true. Afraid I still haven't succeeded:exampleGenerated <- cbind(exampleCurrent, bestCase = switch(as.character(exampleCurrent$off), "FALSE" = "A", "TRUE" = "B"))- DaveRGPswitchcan't accept a vector longer than 1 (try reading the error message). In order for your example to work, you''ll have to loop it, i.e.,sapply(exampleCurrent$off, function(x) switch(as.character(x), "FALSE" = "A", "TRUE" = "B")). But I'd just go with @Svens nice solution. - David Arenburg