Ronny Efronny Ronny Efronny - 18 days ago 10
R Question

Why does R claim my object is not logical?

I have a simple class question here, and I'm getting stumped.
In this one, where I'm only supposed to use

ifelse
. First few lines work fine, but the if the my
x
is logical, the function should turn any
TRUE
into the word "White", and any
FALSE
into the word "Black".

q5 <- function (x) {
ifelse (is.numeric (x),
(div_three <- which (x %% 3 == 0)) &
(not_div_three <- which (x %% 3 != 0)) &
(x [div_three] <- (x [div_three] / 3)) &
(x [not_div_three] <- (x [not_div_three] * 2)),
ifelse (is.character (x),
stop ("Input is a character."),
ifelse (is.logical (x),
(is_true <- which (x == "TRUE")) &
(is_false <- which (x == "FALSE")) &
(x [is_true] <- "WHITE") &
(x [is_false] <- "FALSE"))))
x
}


However, whenever I run
q5 (c(TRUE, TRUE, FALSE, TRUE, TRUE))
for example, I get this error:

Error in (is_true <- which(x == "TRUE")) & (is_false <- which(x == "FALSE")) & :
operations are possible only for numeric, logical or complex types


This vector is definitely logical. I tried turning it into character before inserting the words, and also tried using a new element but it's all the same.
Id love some help figuring out what this message means, given that my element is, in fact, logical.
Thank you!

Answer

replace your code for is.logical(x) with this. error was because in the evaluation "WHITE" & "FALSE" was occuring, because in R, anything inside () gets returned. You can try running x <- "R" and (x<-"R") to see the difference

ifelse (is.logical (x), x <- ifelse(x, "WHITE", "FALSE"))