rdplyrr-car

Trying to recode multiple variables into one?


I'm trying to take three different variables representing partisanship and combine them into one. The data looks like this, where each respondent has data on only one of the three variables as either a 1 or 2:

PARTISANSHIP_D PARTISANSHIP_I PARTISANSHIP_R
1 NA NA
2 NA NA
NA 1 NA

And what I'm trying to create is one variable on a 1:6 scale based on the responses to all three. I've tried to do this using dplyr

survey$partisan <- mutate(survey, partisan = ifelse(PARTISANSHIP_D==1, 6, 
ifelse(PARTISANSHIP_D==2, 5, 
ifelse(PARTISANSHIP_I==1, 4, ifelse(PARTISANSHIP_I==2, 3, ifelse(
PARTISANSHIP_R==2, 2, 1)
)))))

car

survey$partisan <- Recode(survey$PARTISANSHIP_D, "1=6; 2=5", 
survey$PARTISANSHIP_I, "1=4; 2=3",
survey$PARTISANSHIP_R, "1=1; 2=2")

and plain ifelse commands like this:

survey$partisan <- ifelse(survey$PARTISANSHIP_D == 1, 6, 
ifelse(survey$PARTISANSHIP_D == 2, 5,
ifelse(survey$PARTISANSHIP_I == 1, 4, 
ifelse(survey$PARTISANSHIP_I == 2, 3,
ifelse(survey$PARTISANSHIP_R == 2, 2, 1)))))

But none of these is working. Any pointers of what I'm doing wrong?


Solution

  • I got your mutate to work by doing a couple of things: change the NA in your survey dataframe to 0:

    survey[is.na(survey)]<-0
    

    This is because ifelse stops when it encounters an NA.

    And don't assign the mutate result to survey$partisan. Rather, assign it to the whole dataframe:

    survey <- mutate(survey, partisan = ifelse(PARTISANSHIP_D==1, 6, 
                                                    ifelse(PARTISANSHIP_D==2, 5, 
                                                           ifelse(PARTISANSHIP_I==1, 4, ifelse(PARTISANSHIP_I==2, 3, ifelse(
                                                             PARTISANSHIP_R==2, 2, 1)
                                                           )))))