将数据分类为相同大小的组

问题描述

我想将我的数据分成不同的类,每个类的宽度为 10

例如:

第一个数据

   variable
    10
    20
    33
    23
    8
    14
    16
    40

新数据

variable     classify    group classify
    10       10-20             2
    20       20-30             3
    33       30-40             4
    23       20-30             3
    8        0-10              1
    14       10-20             2
    16       10-20             2
    40       40-50             5

解决方法

cut10 的中断一起使用。但要注意间隔的终点。

brks <- seq(from = min(variable %/% 10) * 10,to = (max(variable %/% 10) + 1) * 10,by = 10)
classify <- cut(variable,breaks = brks,include.lowest = TRUE,right = FALSE)
group <- match(classify,levels(classify))

data.frame(variable,classify,group)
#  variable classify group
#1       10  [10,20)     2
#2       20  [20,30)     3
#3       33  [30,40)     4
#4       23  [20,30)     3
#5        8   [0,10)     1
#6       14  [10,20)     2
#7       16  [10,20)     2
#8       40  [40,50]     5

数据

要读入发布的数据,复制并粘贴到 R 会话并运行:

variable <- scan(text = "
10
20
33
23
8
14
16
40
")

dput(variable) 的输出使 SO 用户更简单。

variable <- c(10,20,33,23,8,14,16,40)
,

您可以使用 floor 函数:

df$group_classify <- floor(df$variable/10) + 1
df$classify <- paste((df$group_classify - 1) * 10,df$group_classify * 10,sep = '-')
df

#  variable group_classify classify
#1       10              2    10-20
#2       20              3    20-30
#3       33              4    30-40
#4       23              3    20-30
#5        8              1     0-10
#6       14              2    10-20
#7       16              2    10-20
#8       40              5    40-50

数据

df <- structure(list(variable = c(10,40)),class = "data.frame",row.names = c(NA,-8L))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...