0
votes

I am trying to condense a party ID seven point scale variable (pid_x) from the ANES 2012 data to a dummy variable (democrat = 1 and republican = 0). This entails removing all missing values and excluding independents (4). I can remove NAs, but how would I filter out independents and properly mutate the new variable? Yes, I am very new to R. Much appreciated!

The code below provides the following error:

"Error: Problem with mutate() input party_id_recode. x Can't recycle ..1 (size 2054) to match ..2 (size 3). i Input party_id_recode is `ifelse(pid_x == 1:3, 1, ifelse(pid_x == 5:7, 0))"

library(tidyverse)

anesnew <- anes %>%
  na.omit(anes$pid_x) %>%  
  mutate(party_id_recode = ifelse(pid_x == 1:3, 1,
                              ifelse(pid_x == 5:7, 0)))

enter image description here

1
Please add data using dput or something that we can copy and use. Also show expected output for the data shared. Read about how to ask a good question and how to give a reproducible example.Ronak Shah

1 Answers

1
votes

Reproducible data and expected output would be very useful, but it looks like your ifelse() statement hasn't been constructed properly, and could be simplified:

anesnew <- anes %>%
  filter(!is.na(pid_x), pid_x != 4) %>%
  mutate(party_id_recode = case_when(pid_x < 4 ~ 1,
                                     pid_x > 4 ~ 0))

With the following sample data:

anes <- tibble(pid_x = c(1, 2, 3, 4, 5, 6, 7, NA))

The results are:

# A tibble: 6 x 2
  pid_x party_id_recode
  <dbl>           <dbl>
1     1               1
2     2               1
3     3               1
4     5               0
5     6               0
6     7               0