0

I have a data frame contain a column for age(numeric). I used this code to categorize them ta into ages groups? however, the variable appears as false true NA

My data name metsother

agecategory <- metsother %>% 
   mutate(metsother$Age == case_when(
     metsother$Age >= 18 & metsother$Age <= 40 ~ "Category 1",
     metsother$Age >= 41 & metsother$Age <= 60 ~ "Category 2",
     metsother$Age >= 61 & metsother$Age >= 80 ~ "Category 3"))

enter image description here

Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • 2
    1) Don't use `$` in `dplyr` pipe. 2) `mutate(metsother$Age == case_when(....)` should be `mutate(Age = case_when(...)`. `==` is for comparison, `=` for assignment. 3) See this https://stackoverflow.com/questions/12979456/categorize-numeric-variable-into-group-bins-breaks for a simpler method. – Ronak Shah Aug 31 '21 at 09:26
  • `Age >= 61 & Age >= 80` is the same as `Age >= 80`. Did you misstyped `Age <= 80`? – Martin Gal Aug 31 '21 at 10:12
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 31 '21 at 11:31
  • Thank you for help, I mistook used == instead of = and also a mistake in age <= 80 ...I edited them and worked many thanks – kirellos said Aug 31 '21 at 12:02

2 Answers2

0

This will give you a new column Age_cat to your dataframe metsother

library(dplyr)
metsother %>% 
  mutate(Age_cat = case_when(Age >= 18 & Age <= 40 ~ "Category 1",
                         Age >= 41 & Age <= 60 ~ "Category 2", 
                         Age >= 61 & Age >= 80 ~ "Category 3",
                         TRUE ~ NA_character_))
TarJae
  • 72,363
  • 6
  • 19
  • 66
-1

I think the problem is on the double equal after the first metsother$Age. You are using an comparison instead of an assigment.

agecategory<- metsother %>% mutate(
          metsother$Age = case_when(
                             metsother$Age >= 18 & metsother$Age <= 40 ~ "Category 1",
                             metsother$Age >= 41 & metsother$Age <= 60 ~ "Category 2", 
                             metsother$Age >= 61 & metsother$Age >= 80 ~ "Category 3"
))
JMenezes
  • 1,004
  • 1
  • 6
  • 13