I have a dataframe with ages and my objective is to split those ages into groups.
I found the way to do it, that is using cut from base R. However, I would like to change the format of the output. I saw one way in this post but as someone says, I lose information contained in the original notation.
The code:
set.seed(1234)
Age <- floor(runif(25, min=18, max=75))
df <- data.frame(Age)
mybreaks <- seq(min(df$Age)-1, to=max(df$Age)+10, by=10)
df$groups_age <- cut(df$Age, breaks = mybreaks, by=10)
label_interval <- function(breaks) {
paste0("(", breaks[1:length(breaks) - 1], "-", breaks[2:length(breaks)], ")")
}
df$groups_age_2 <- cut(df$Age, breaks = mybreaks, labels = label_interval(mybreaks))
df[7:12, ]
# Age groups_age groups_age_2
# 7 18 [17,27) (17-27)
# 8 31 [27,37) (27-37)
# 9 55 [47,57) (47-57)
# 10 47 [47,57) (37-47)
# 11 57 [57,67) (47-57)
# 12 49 [47,57) (47-57)
As you can see, the column "group_age" is the output from cut and the column "group_age2" is the result from using the function label_interval (which someone wrote in the previous post).
It could be a good solution, but I lose information.
For example, in rows 7 and 8, we see 2 different ages which have different groups. Both contain 27, which is not correct.
I would like to have row 8 like (28-37) but I don't know how to add it in the function, in order to do it with the entire dataframe.
Does anyone know how to do it?