Reputation: 9765
Can someone explain why only some of the numbers are being converted to the strings high and low?
set.seed(1)
df <- data.frame(npitotal=ceiling(runif(30,0,40)))
df$npitotal[df$npitotal >= 22] <- "high"
df$npitotal[df$npitotal < 22] <- "low"
df$npitotal
# [1] "low" "low" "high" "high" "9" "high" "high" "high"
# [9] "high" "3" "9" "8" "high" "low" "high" "low"
#[17] "high" "high" "low" "high" "high" "9" "high" "6"
#[25] "low" "low" "low" "low" "high" "low"
Upvotes: 2
Views: 45
Reputation: 9765
My eventual solution was to use recode
in the car package:
library(car)
recode(df$npitotal,"0:21='low';22:40='high'")
Note that 0:21 is [0,21] (so 20.99 evaluates to "low: in this case)
Thanks to @Jay for explaining the reason this causes a problem:
After you do your first conversion it becomes a character vector - so the second less than is not being evaluated numerically but as a character.
Upvotes: 2