To create an Age_Group variable, you can use the cut() function in R. Here's an example:
# create a sample dataset
df <- data.frame(age = c(18, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75))
# create Age_Group variable
df$Age_Group <- cut(df$age,
breaks = c(0, 24, 34, 44, 54, 64, Inf),
labels = c("18-24", "25-34", "35-44", "45-54", "55-64", "65+"),
right = FALSE)
print(df)
In this example:
breaks specifies the age ranges for each group. The Inf value represents all ages above 64.
labels specifies the labels for each age group.
right = FALSE means that the intervals are left-closed (i.e., the lower bound is included).
The resulting Age_Group variable will categorize the ages into the specified groups.
Using dplyr package
You can also use the mutate() function from the dplyr package along with cut() or case_when() to create the Age_Group variable.
# install and load dplyr package
install.packages("dplyr")
library(dplyr)
# create a sample dataset
df <- data.frame(age = c(18, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75))
# create Age_Group variable using cut()
df <- df %>%
mutate(Age_Group = cut(age,
breaks = c(0, 24, 34, 44, 54, 64, Inf),
labels = c("18-24", "25-34", "35-44", "45-54", "55-64", "65+"),
right = FALSE))
# or using case_when()
df <- df %>%
mutate(Age_Group = case_when(
age >= 18 & age <= 24 ~ "18-24",
age >= 25 & age <= 34 ~ "25-34",
age >= 35 & age <= 44 ~ "35-44",
age >= 45 & age <= 54 ~ "45-54",
age >= 55 & age <= 64 ~ "55-64",
age >= 65 ~ "65+",
TRUE ~ NA_character_
))
print(df)
Both methods will produce the same result, but the case_when() approach can be more flexible if you need to handle complex conditions or non-numeric data.