Issues with recode() in dplyr to recode multiple observations at a time

I have a dataset where one of the columns/variables is "Ethnicity", coded with 12 different racial groups. I want to recode the variable as containing three values only, since I'm only interested in "White" and "Black or African American", and want everything else to be recoded as "Other". I used the code below, but obtained the following error. I know I can enter each racial group individually ("Hispanic" = "Other", "Asian" = "Other), but is there a way to do it more efficiently? I'm sure there is, but it's beyond my R knowledge. Thanks!

New_ethnicity <- data %>%
select(Ethnicity) %>%
mutate(Ethnicity = recode(Ethnicity, !c("White", "Black or African American") = "Other"))

Error: unexpected '=' in:
" select(Ethnicity) %>%
mutate(Ethnicity = recode(Ethnicity, !c("White", "Black or African American") ="

Try case_when

New_ethnicity <- data %>%
select(Ethnicity) %>%
mutate(Ethnicity = case_when(
  !Ethnicity %in% c("White", "Black or African American") ~ "Other",
  TRUE ~ Ethnicity
))

This example could also be run with if_else

2 Likes

Thanks! That worked!

Just for completeness, here's how to do it with recode().

library(dplyr, warn.conflicts = FALSE)

Ethnicity <- c("White", "Black or African American", "Hispanic", "White", "Asian", "Black or African American")

Ethnicity
#> [1] "White"                     "Black or African American"
#> [3] "Hispanic"                  "White"                    
#> [5] "Asian"                     "Black or African American"

recode(Ethnicity, "White" = "White", "Black or African American" = "Black or African American", .default = "Other")
#> [1] "White"                     "Black or African American"
#> [3] "Other"                     "White"                    
#> [5] "Other"                     "Black or African American"

Created on 2020-10-22 by the reprex package (v0.3.0)

2 Likes

This topic was automatically closed 7 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.