Chris J
Chris J

Reputation: 13

Recoding continuous variable into categorical with *specific" categories, in R using Tidyverse

I found this helpful answer to almost the same question, but it doesn't quite do what I need.

I have respondents' age, a continuous variable, and I'd like to recode it to categorical using tidyverse. The link above includes explanations of the functions cut_number(), cut_interval(), and cut_width(), but the reason those don't work for me is because I'd like to recode into categories that I've already determined ahead of time, namely, the ranges 18-34, 35-54, and 55+. None of those cut functions allow me to do this (or at least I didn't see how).

I was able to get my code to run without tidyverse, using:

data$age[data$"Age(Self-report)"<35] <- "18-34"
data$age[data$"Age(Self-report)">34 & data$"Age(Self-report)"<55] <- "35-54"
data$age[data$"Age(Self-report)">55] <- "55+"

but I'm trying to be consistent in my coding style and would like to learn how to do this in Tidyverse. Thanks for any and all help!

Upvotes: 1

Views: 2077

Answers (1)

stefan
stefan

Reputation: 123783

A tidyverse approach would make use of dplyr::case_when to recode the variable like so:

data %>% 
  mutate(age = case_when(
    `Age(Self-report)` < 35 ~ "18-34",
    `Age(Self-report)` > 34 & `Age(Self-report)` < 55 ~ "35-54",
    `Age(Self-report)` > 55 ~ "55+"
  ))

Upvotes: 1

Related Questions