Reputation: 939
Hi I created a group of age bins in R:
labs <- c(paste(0, "", sep=""), paste(1,9, sep="-"),paste(seq(10, 80, by = 10), seq(20-1, 90-1, by =10), sep="-", paste(90, "+", sep=""))
out "0" "1-9" "10-19" "20-29" "30-39" "40-49" "50-59" "60-69" "70-79" "80-89" "90+"
How can I sort a column of ages from a df into the appropriate age group in labs? How can I use cut function?
Expected Output will be:
Age AgeGroup
5 1-9
0 0
15 10-19
69 70-79
100 90+
Upvotes: 1
Views: 2412
Reputation: 3914
# Set seed for reproducibility of results since I use sample() function
# to generate values for Age variable
set.seed(12345)
#create a numeric variable Age
Age <- sample(0:110, 100, replace = TRUE)
# Use cut() function to associate each value with a specific age group
AgeGroup <- cut(Age,
right=FALSE,
breaks = c(0,1,(1:9)*10,1000),
labels = c("0","1-9",
paste((1:8)*10,"-",(1:8 + 1)*10 -1),"90+"))
# create a data frame (if necessary)
df <- data.frame(Age, AgeGroup)
head(df)
# 1 80 80 - 89
# 2 97 90+
# 3 84 80 - 89
# 4 98 90+
# 5 50 50 - 59
# 6 18 10 - 19
Upvotes: 1