Reputation: 5
I am interested in turning a character variable with 72 options into a factor with four options so that the observations are separated into one of three zip codes (factors 1-3); if they are not one of those zip codes, I want the observation to get a 0 for zip. Thank you.
Fct2 <- factor(hs$zip, 1 == 35758, 2 == 35811, 3 == 35749, 0 ==....??)
Upvotes: 0
Views: 41
Reputation: 389135
You can use dplyr::recode
:
hs$zip2 <- dplyr::recode(hs$zip, `35758` = 1,
`35811` = 2, `35749` = 3, .default = 0)
Upvotes: 0
Reputation: 740
zip = c(35758, 35811,35749,34234,34324)
Fct2 <- case_when(zip == 35758 ~ 1,
zip == 35811 ~ 2,
zip == 35749 ~ 3,
TRUE ~ 0) %>% as.factor()
Upvotes: 2