RL_Pug
RL_Pug

Reputation: 857

How to use a ifelse or dplyr in R?

print(mydata)
Race    Ethnicity
White   Hispanic
White   Non-Hispanic
Black   Unknown
Asian   Non-Hispanic
White   NA
White   Non-Hispanic

I want a new column. If someone is Hispanic, I would like for them to be Hispanic in the new column regardless of race. But if their ethnicity is Non-Hispanic, Unknown, or NA. I would want to take their Race instead.

This my desired output

print(mydata)
Race    Ethnicity       RaceEthnic
White   Hispanic          Hispanic
White   Non-Hispanic      White
Black   Unknown           Black
Asian   Non-Hispanic      Asian
White   NA                White
White   Non-Hispanic      White

I tried something like this but it didn't work

data <- data %>%
  mutate(EthnicRace = ifelse(Ethnicity == "Hispanic" ~ "Hispanic", Race))

Upvotes: 1

Views: 111

Answers (2)

csgroen
csgroen

Reputation: 2541

You were almost there:

data <- data %>%
  mutate(EthnicRace = ifelse(Ethnicity == "Hispanic", "Hispanic", Race))

Upvotes: 3

akrun
akrun

Reputation: 887048

The ~ is used in case_when and not in ifelse (assuming the 'Ethnicity' and 'Race' are both character class

library(dplyr)
mydata %>%
    mutate(EthnicRace = case_when(Ethnicity == "Hispanic"~ "Hispanic",
                TRUE ~ Race))
#  Race    Ethnicity EthnicRace
#1 White     Hispanic   Hispanic
#2 White Non-Hispanic      White
#3 Black      Unknown      Black
#4 Asian Non-Hispanic      Asian
#5 White         <NA>      White
#6 White Non-Hispanic      White

Or another option is replace

mydata %>% 
   mutate(EthnicRace = replace(Race, Ethnicity == "Hispanic", "Hispanic"))

Upvotes: 2

Related Questions