将数值变量分类为组/箱/中断 [英] Categorize numeric variable into group/ bins/ breaks

查看:72
本文介绍了将数值变量分类为组/箱/中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数字变量(年龄)分类为由间隔定义的组,因此它不会是连续的.我有这个代码:

I am trying to categorize a numeric variable (age) into groups defined by intervals 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() :

先编一些样本数据

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)

这篇关于将数值变量分类为组/箱/中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆