I have a database with a list of patients and their city of residence (1-34) that I would like to assign regions to (1-8). How can I add a column that assigns a region to each patient given their city? For example, Region 1 is composed of cities 1, 2, 3, 4, 5, and 8.
Thank you for any help you can provide.
I attempted to use group_by commands but have been getting repeated errors.
df1 <- df %>%
mutate(
cities = fct_collapse(
cities,
"1" = c("1", "2", "3", "4","5","8"),
"2" = c("10", "24"),
"3" = c("6", "7", "15", "16"),
"4" = c("20", "21", "22", "28", "29"),
"5" = c("9", "17", "18", "19"),
"6" = c("25", "26", "27", "30", "34"),
"7" = c("11", "12", "13", "14"),
"8" = c("23", "31", "32", "33")))
For some reason I am returning a new cities column with only 6 groups (regions). Any idea what may be going wrong? Thank you so much for any help you can offer.
You're redefining the "cities" column in your
mutate()call instead of creating a new "region" column.Try:
Here's an alternative where "cities" doesn't have to be a factor: