Collapse Factor Levels

Hello Everyone,

I am trying to collapse the levels for one of my categorical variables. Below is the original factor and levels.

RD_E$RACE <- factor(RD_E$RACE,
levels = c(1,2,3,4,5,6,7),
labels = c("white","black","Hispanic","Asian","Indian",
"Hawian","Other"))

I tried using the below code to collapse into 2 level White and Non-White.
RD_E %>%
mutate(RACE = fct_collapse(RACE,
White = c(1),
Non-White = c(2,3,4,5,6,))) %>%
pull(RACE)%>%
levels()

I am getting the below error. Any advice how to overcome this?
Error in pull(RACE) : object 'RACE' not found

Thanks in advance

I think this does what you want.

RD_E <- data.frame(RACE = c("white", "black", "Hispanic", 
                           "Asian", "Indian", "Hawian", "Other"))
RD_E$RACE <- factor(RD_E$RACE, levels = c("white", "black", "Hispanic", 
                                          "Asian", "Indian", "Hawian", "Other"))
RD_E %>%
  mutate(RACE = forcats::fct_collapse(RACE,
                             White = c("white"),
                             other_level = "Non-White")) %>%
  pull(RACE)%>%
  levels()                   

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.