Can't get case_when to write non-number values...

I can get case_when to write a NUMBER in a data frame, but not a string of text.

My code is like this:

df$Recoded_q1 <- case_when(
(df$q1 == 1 | df$q1 == 2) ~ 1,
(df$q1 == 3 | df$q1 == 4) ~ 2,
(df$q1 == 5 | df$q1 == 6) ~ 3,
TRUE ~ as.numeric(df$q1)

All works well like this, but I can't change the 1, 2, and 3 to text-based, categorical names like "low", "medium", and "high".

Any insight? I've tried double quotes and single quotes both and get errors.

Did you forget to change the as.numeric in the TRUE condition to as.character? I did at first and got an error. This works for me.

df <- data.frame(q1 = 1:6)

df$Recoded_q1 <- case_when(
  (df$q1 == 1 | df$q1 == 2) ~ "low",
  (df$q1 == 3 | df$q1 == 4) ~ "med",
  (df$q1 == 5 | df$q1 == 6) ~ "high",
  TRUE ~ as.character(df$q1))

That works, thanks!!

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.