-1

I have this dataset:

enter image description here

I need to make a new age range with the existing one and combine 25-39 with 40-59. To make it simple to understand; one column named age_range <- c(18-24, 25-39,25-39,40-59,40-59,60+)

i need to make a new age range as new_age_range <- c(18-24, 25-59,60+)

  • Does this answer your question? [Combine factor levels](https://stackoverflow.com/questions/30522594/combine-factor-levels) – Limey Jun 29 '22 at 15:01
  • 1
    There are several options to recode a variable, using e.g. `ifelse` you could do `new_age_range <- ifelse(age_range %in% c("25-39", "40-59"), "25-59", age_range)`. – stefan Jun 29 '22 at 15:07
  • 1
    thanks @stefan, if_else worked out perfectly. – Gorkem Tunc Jun 29 '22 at 21:04
  • Great. Just a reminder for the future and to avoid your question from being downvoted. Try to provide a snippet of your data and the code you tried. For more see [how to make a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – stefan Jun 29 '22 at 21:10
  • indeed I provided my data's image by the link where it writes "enter image description here". I didin' shared the codes I tried because they didin't worked out, and I didn't remember recoding and if_else! but anyways thanks for the solution and advice. – Gorkem Tunc Jun 29 '22 at 21:43

1 Answers1

0

Another option (based in Tidyverse) is to use the fantastic case_when() function to specify a new column called new_age_range. The case_when() function tests to see whether age_range contains either "25-39" or "40-59" and if it does it recodes this as "25-59". If the age_range column does not contain these values then it simply returns their original value.

age_data <- tibble(age_range = c("18-24", "25-39", "40-59", "60+"))

age_data %>%
  mutate(new_age_range = case_when(age_range %in% c("25-39", "40-59") ~ "25-59",
                                   TRUE ~ age_range))

The case_when() works by testing the expression to the left of the ~ sign. If the first expression is true, then it assigns the value to the right of the ~ sign. If it is false, then it evaluates the next expression, and so on. The benefit of this method is that when you have a lot of nested ifelse() statements, you can substitute them with a single case_when() function.

alphabetac
  • 36
  • 3
  • Thanks for the answer @ alphabetac. At first I used if_else as @stefan proposed till I found out that I had not one but 3 age ranges that I need to recode. It is where case_where came to the rescue! as in my case, case_when is the right recoding function – Gorkem Tunc Jul 03 '22 at 12:40