Bioinformatician
Bioinformatician

Reputation: 9

mutate case _when error in R

Can someone tell me what is wrong with this chunk of code:

df %>% mutate(age2=case_when(
    age %in% 0:20 ~ "A"
    age %in% 20:40 ~ "B"
    age %in% 40:60 ~ "C"
    age %in% 60:80 ~ "D"
    age %in% 80:100 ~ "E"
     T ~ ""))

I get error saying: Error: unexpected symbol in: "age %in% 0:20 ~ "A" I believe ~ is the problem, but not sure how to solve it.

Thank you

Upvotes: 0

Views: 1975

Answers (1)

duckmayr
duckmayr

Reputation: 16920

You need commas between the cases (source):

df %>% mutate(age2=case_when(
    age %in% 0:20 ~ "A",
    age %in% 20:40 ~ "B",
    age %in% 40:60 ~ "C",
    age %in% 60:80 ~ "D",
    age %in% 80:100 ~ "E",
     T ~ ""))

However, you also might want to think about www's comment in the case that age might take a non-integer value.

Upvotes: 2

Related Questions