0

I am trying to do an ifelse statement that tests if a variable is equal to a series of character strings. In dummy data, I am trying the following:

mtcars$mpg <- as.character(mtcars$mpg)
table(ifelse(mtcars$mpg == c("21", "18.1", "14.3"), "TRUE", "FALSE"))

I want this to produce 4 Trues, and 28 Falses.

tchoup
  • 971
  • 4
  • 11
  • 3
    `table(mtcars$mpg %in% c("21", "18.1", "14.3"))` see `?match` – M.Viking Jan 10 '23 at 00:13
  • 1
    Use %in%: `table(ifelse(mtcars$mpg %in% c("21", "18.1", "14.3"), "TRUE", "FALSE"))` – TheDza Jan 10 '23 at 00:36
  • 1
    To make clear why the two statements above are correct, when you use `==` on a vector ist looks through `mtcars$mpg` for that full vector NOT the individual values. Using %in% it searches to see if any given value is IN the vector, then it assigns the boolean. But I would try `table(ifelse(mtcars$mpg %in% c("21", "18.1", "14.3"), TRUE, FALSE))` because the "" make the strings not true R boolean values – sconfluentus Jan 10 '23 at 01:09

0 Answers0