Reputation: 2431
I R, I want to add new character group 'region_new ', it seems 'if else' not work. Any one can help ? thank
test_data <- data.frame(region=LETTERS)
test_data$region_new <- ''
if (test_data$region in c('a','b','c')){
test_data$region_new <- 'Level_A'
} else if (test_data$region in c('d','x','z')) {
test_data$region_new <- 'Level_B'
} else {
test_data$region_new <- 'Level_Other'
}
Upvotes: 0
Views: 52
Reputation: 388982
You need vectorized ifelse
instead of if
/else
. Also use %in%
instead of in
.
You can also use case_when
from dplyr
-
library(dplyr)
test_data <- data.frame(region=LETTERS)
test_data %>%
mutate(region_new = case_when(region %in% c('A','B','C') ~ 'Level_A',
region %in% c('D','X','Z') ~ 'Level_B',
TRUE ~ 'Level_Other'))
Another option is to use fct_collapse
from forcats
.
test_data %>%
mutate(region_new = forcats::fct_collapse(region,
Level_A = c('A','B','C'),
Level_B = c('D','X','Z'),
other_level = 'Level_Other'))
Upvotes: 1