Home > Net >  New variable based on values from existing variable
New variable based on values from existing variable

Time:05-20

I have a dataset where one variable is "ideology" with answers ranging from 1-10. I am looking to create a variable called "leftwing" for respondents who answered 1,2,3 or 4, with the end result being 1=leftwing, 0=not leftwing (anyone who answered 5,6,7,8,9,10)

I have tried this code:

examopg3 <- examopg2 %>%
  group_by(ideology) %>%
  mutate(leftwing = ideology == 1,2,3,4)

But the new variable only had the value "False" for all answers.

Thank you for helping me:)

CodePudding user response:

You need this:

 examopg3 <- examopg2 %>%
         mutate(leftwing = case_when(
                     ideology %in% c(1,2,3,4) ~ 1,
                     TRUE ~ 0))
  •  Tags:  
  • r
  • Related