case_when new category

Hello I have a variable and based on it I wanted to generate another variable when the first one is between certain values. I am trying with this code, but it gives me error. I want to create values from 0 to 4 to "category" the new variable.

library(tidyverse)
my_data <- tibble(Var_1 = c(1, 5, 8, 90, 1500, 350, 1200, 450,125,250,300)
                  
my_data %>%
mutate(category = case_when(
Var_1 < 50 ~ 0,
Var_1<= 99  & Var_1>= 50 ~ 1,
Var_1<= 199 & Var_1>= 100 ~ 2,
Var_1<= 499 & Var_1>= 200 ~ 3,
Var_1<= 500 ~ 4,
TRUE ~ Var_1))```

Nothing wrong with it except in your my_data bit, which is missing the closing ).

my_data <- tibble(Var_1 = c(1, 5, 8, 90, 1500, 350, 1200, 450,125,250,300)) # missing the closing `)`
# A tibble: 11 x 2
   Var_1 category
   <dbl>    <dbl>
 1     1        0
 2     5        0
 3     8        0
 4    90        1
 5  1500     1500
 6   350        3
 7  1200     1200
 8   450        3
 9   125        2
10   250        3
11   300        3
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.