Use case_when in Mutate to collapse values across variable

I have a variable with values ranging from 1 to 5. I want to collapse values
1 and 2 = 1,
3 = 2,
4 and 5 = 3
When I run the following dplyr tools, I get an error. Below is an example:
Sample Data:
df <- structure(list(R1 = c(2, 1, 2, 2, 3, 4, 5, 5, 5, 5, 4, 3, 3, 2, 2, 1, 1, 4, 4, 1)),
row.names = c(NA,
-20L), class = c("data.frame"))
Code:
df %>%
mutate(R1 = case_when(R1 <= 2 ~ "1",
R1 > 3 ~ "3",
R1 = 3 ~ "2"))

Error:
Error: LHS of case 3 (3) must be a logical vector, not a double vector

In your last condition you need to use == instead of =. Also, I am not sure what ra2_1r is. Try

df %>%
  mutate(R1 = case_when(R1 <= 2 ~ "1",
                        R1 > 3 ~ "3",
                        R1 == 3 ~ "2"))
2 Likes

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.