1

I have likert scale responses ranging from 1:7 where 8 is "don't know". I'd like to recode 1:3, 4, 5:7 as a new variable where instead of a vector with 8 different responses, I have a new variable that consolidates 1:3, 4, and 5:7 and ignores "don't know" responses. I want to call it "pid3." The vector comes from imported polling data. It is called "pid7." It is very long so I cannot manually re-type it. Sorry- this is my first time asking a question here. I am not fluent in R.

library(dplyr)
class(pop$pid7)
pid3 <- data.frame(x = c("DEMOCRAT", "INDEPENDENT", "REPUBLICAN"))
pid7 <- recode(pop$pid7, x_recoded = recode(x, "DEMOCRAT" = 1:3, "INDEPENDENT" = 4, "REPUBLICAN" = 5:7, "NA"= 8))
dplyr::recode(pop$pid7, "DEMOCRAT" = 1,2,3, "INDI" = 4, "REPUBLICAN" = 5,6,7, "NA" = 8) 

these are the things I've tried. I don't understand what order I need to do things in.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • you can do this with `factor` you dont need a package `factor(pop$pid7, 1:7, c('d', 'd', 'd', 'i', 'r', 'r', 'r'))` – rawr Mar 01 '22 at 11:19

2 Answers2

0

Taking suggestions from here : How to recode multiple values in vector into one value?

x <- sample(1:8, 15, replace = T)
x
#>  [1] 8 1 7 3 1 5 3 8 2 7 3 7 1 5 6

keysvals <- setNames(rep(c("DEMOCRAT", "INDEPENDENT", "REPUBLICAN", NA), c(3,1,3,1)), 1:8)
dplyr::recode(x, !!!keysvals)
#>  [1] NA           "DEMOCRAT"   "REPUBLICAN" "DEMOCRAT"   "DEMOCRAT"  
#>  [6] "REPUBLICAN" "DEMOCRAT"   NA           "DEMOCRAT"   "REPUBLICAN"
#> [11] "DEMOCRAT"   "REPUBLICAN" "DEMOCRAT"   "REPUBLICAN" "REPUBLICAN"
slowowl
  • 664
  • 1
  • 13
0

I would recommend using case_when from `dplyr.

The below example recodes 8 (or really anything that doesn't match 1 through 7 before it) to NA symbol, and not character value "NA". However, if you did want to use "NA" you can substitute with that.

set.seed(39)

df <- data.frame(
  x = sample(1:8, 10, replace = T)
)

library(dplyr)

df %>%
  mutate(x_recoded = case_when(
    x %in% 1:3 ~ "DEMOCRAT",
    x == 4 ~ "INDEPENDENT",
    x %in% 5:7 ~ "REPUBLICAN",
    TRUE ~ NA_character_
  ))

Output

   x   x_recoded
1  1    DEMOCRAT
2  3    DEMOCRAT
3  8        <NA>
4  8        <NA>
5  2    DEMOCRAT
6  5  REPUBLICAN
7  6  REPUBLICAN
8  8        <NA>
9  4 INDEPENDENT
10 5  REPUBLICAN
Ben
  • 28,684
  • 5
  • 23
  • 45