Here's a solution using ifelse
col = ifelse(x<4, "red",
ifelse(x>3 & x<89 | x>93 & x<155, "black",
ifelse(x>88 & x<94, "blue", "purple")))
You need ifelse
becase ifelse
is vectorized, if
is not, therefore ifelse
will check each element in your vector and filled with the corresponding color, while if
only checks for the first element.
A simple example to note this:
x <- 1:6 # a sample vector
# using `if` to check condition and assigning a value, it'll fail
if(x<4){
"red"
} else {
"other color"
}
# suing `ifelse` for the same task. It'll win
ifelse(x<4, "red", "other color")
from the helpfile
ifelse
returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE