Help with Case_when for categorical variables

Hello,

Thank you in advance for any help. I'm a complete beginner with R. I am
working on an assignment in which I have an outcome variable listed as:

0_hrs
0_to_1_hr
1_hr
2_hr
3_hr
4_hr
More_4_hr
NA

I need to make it into two groups, the first group containing: 0_hrs,
0_to_1_hr, 1_hr, 2_hr; the second group containing: 3_hr, 4_hr, More_4_hr.
I've tried writing this code:

nhanes2 <- nhanes %>%
mutate(TVHrsDay = case_when(
TVHrsDay = 0_hrs ~ "0 - 2 Hours",
TVHrsDay = 0_to_1_hr ~ "0 - 2 Hours",
TVHrsDay = 1_hr ~ "0 - 2 Hours",
TVHrsDay = 2_hr ~ "0 - 2 Hours",
TVHrsDay = 3_hr ~ "3 Hours or Greater",
TVHrsDay = 4_hr ~ "3 Hours or Greater",
TVHrsDay = More_4_hr ~ "3 Hours or Greater",
TRUE ~ NA_character_),
TVHrsDay = factor(TVHrsDay, levels = c('0 - 2 Hours','3 Hours or
Greater')))

epitab(nhanes2$TVHrsDay,nhanes2$RegularMariJ, method='oddsratio')

But, I get an error message saying that: Error: unexpected input in: "
mutate(TVHrsDay = case_when(TVHrsDay = 0_"

If anybody could me figure this out to get it to run properly I would be
very appreciative!

Thank you!

Use quotation marks around the strings:

nhanes2 <- nhanes %>%
  mutate(TVHrsDay = case_when(
    TVHrsDay = "0_hrs" ~ "0 - 2 Hours",
    TVHrsDay = "0_to_1_hr" ~ "0 - 2 Hours",
    TVHrsDay = "1_hr" ~ "0 - 2 Hours",
    TVHrsDay = "2_hr" ~ "0 - 2 Hours",
    TVHrsDay = "3_hr" ~ "3 Hours or Greater",
    TVHrsDay = "4_hr" ~ "3 Hours or Greater",
    TVHrsDay = "More_4_hr" ~ "3 Hours or Greater",
    TRUE ~ NA_character_),
    TVHrsDay = factor(TVHrsDay, levels = c('0 - 2 Hours','3 Hours or
Greater')))

You could also just do this instead to save you some typing:

nhanes2 <- nhanes %>%
  mutate(TVHrsDay = case_when(
    TVHrsDay %in% c("0_hrs", "0_to_1_hr", "1_hr", "2_hr")  ~ "0 - 2 Hours",
    TVHrsDay %in% c("3_hr", "4_hr", "More_4_hr") ~ "3 Hours or Greater",
    TRUE ~ NA_character_),
    TVHrsDay = factor(TVHrsDay, levels = c('0 - 2 Hours','3 Hours or Greater')))
1 Like

Thank you so much! People like you are the salt of the earth!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.