【问题标题】:R - How to sort age values into age groupR - 如何将年龄值分类到年龄组
【发布时间】:2019-10-31 15:48:35
【问题描述】:

您好,我在 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+

【问题讨论】:

  • 您的预期输出是什么。你需要的是cut(age, breaks = c(1, seq(10, 90, by = 10), Inf))
  • 在上面添加了预期的输出
  • 我在 cut.default(df$Age, breaks = c(1, seq(10, 90, by = 10), : 'x' must be numeric 中遇到错误
  • 您的年龄列是数字吗?如果不这样做df$Age &lt;- as.numeric(as.character(df$Age))
  • 我建议将“年龄”转换为numeric

标签: r


【解决方案1】:
# 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

【讨论】:

  • 嗨,Katia,您的代码运行良好!只有一个问题,age = 0、10、20 等的值似乎没有正确排序。需要添加right = FALSE 才能正常工作。谢谢!
  • @spidermarn 嗨,你说得对。我立即进行了此编辑,但不知何故没有保存(我可能忘记单击“保存”按钮。我再次进行了更改,它现在应该在那里。感谢您注意到它。--Katia跨度>
猜你喜欢
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多