R代码将年龄分为组/箱/休息时间 [英] R code to categorize age into group/ bins/ breaks
本文介绍了R代码将年龄分为组/箱/休息时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将年龄分组,因此年龄不会连续。我有以下代码:
I am trying to categorize age into group so it will not be continuous. I have this code:
data$agegrp(data$age>=40 & data$age<=49) <- 3
data$agegrp(data$age>=30 & data$age<=39) <- 2
data$agegrp(data$age>=20 & data$age<=29) <- 1
以上代码在生存包下不起作用。它给我:
the above code is not working under survival package. It's giving me:
invalid function in complex assignment
您能指出错误在哪里吗? data
是我正在使用的数据框。
Can you point me where the error is? data
is the dataframe I am using.
推荐答案
我将在此处使用 findInterval()
:
首先,构成一些样本数据
First, make up some sample data
set.seed(1)
ages <- floor(runif(20, min = 20, max = 50))
ages
# [1] 27 31 37 47 26 46 48 39 38 21 26 25 40 31 43 34 41 49 31 43
使用 findInterval()
可以对年龄向量进行分类。
Use findInterval()
to categorize your "ages" vector.
findInterval(ages, c(20, 30, 40))
# [1] 1 2 2 3 1 3 3 2 2 1 1 1 3 2 3 2 3 3 2 3
或者,按照注释中的建议,在这里 cut()
也很有用:
Alternatively, as recommended in the comments, cut()
is also useful here:
cut(ages, breaks=c(20, 30, 40, 50), right = FALSE)
cut(ages, breaks=c(20, 30, 40, 50), right = FALSE, labels = FALSE)
这篇关于R代码将年龄分为组/箱/休息时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文