r - R - 如何将年龄值分类到年龄组
问题描述
嗨,我在 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+"
如何将 df 中的一列年龄分类到实验室中的适当年龄组中?如何使用剪切功能?
预期输出将是:
Age AgeGroup
5 1-9
0 0
15 10-19
69 70-79
100 90+
解决方案
# 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
推荐阅读
- django - Django以特定数字开头的ID?
- magento - 如何使子菜单保持在顶部?
- javascript - 将 React Element 附加到正文的正确方法是什么?
- c# - 如何使用元组实现此代码?
- python - 如何在我的网页上使用我的数据框中的列名和唯一值生成动态选择字段?
- python - 如何迭代更新字典的值并将每个表示添加到列表中
- powershell - 尽管有正在运行的服务,Docker 容器仍会退出
- python - 比较不同曲线的均方误差
- rust - 检查 Rust 是否正在运行测试构建
- python - 如何在 Power BI 中使用 Python 脚本实现插补?