使用R获取对应关系表,将每个变量分为四个间隔

时间:2019-03-16 22:43:22

标签: r

我有以下数据,我需要获取对应表,将每个变量分为四个类或间隔

data2 <- data.frame(heigth = c(1.25, 1.28, 1.27, 1.21, 1.22, 1.29, 1.30, 
                               1.24, 1.27, 1.29, 1.23, 1.26, 1.30, 1.21,
                               1.28, 1.30, 1.22, 1.25, 1.20, 1.28, 1.21,
                               1.29, 1.26, 1.22, 1.28, 1.27, 1.26, 1.23,
                               1.22, 1.21),
                  weigth = c(32, 33, 31, 34, 32, 31, 34, 32, 32, 35,
                           31, 35, 34, 33, 33, 31, 35, 32, 31, 33,
                           33, 32, 34, 34, 35, 31, 34, 33, 35, 34 ))

mytable <- with(datos2, table(estatura,peso))

            peso
estatura 31 32 33 34 35
    1.2   1  0  0  0  0
    1.21  0  0  2  2  0
    1.22  0  1  0  1  2
    1.23  1  0  1  0  0
    1.24  0  1  0  0  0
    1.25  0  2  0  0  0
    1.26  0  0  0  2  1
    1.27  2  1  0  0  0
    1.28  0  0  3  0  1
    1.29  1  1  0  0  1
    1.3   1  0  0  2  0

我有对应表,但我需要将其分为四个类别

2 个答案:

答案 0 :(得分:1)

可能是这样的事情?我使用包data.table并使用第一到第四分位数来设置类别。

library(data.table)
setDT(data2)
table(data2[,.(cut(heigth,quantile(heigth)),cut(weigth,quantile(weigth)))])

#        V2
# V1            (31,32] (32,33] (33,34] (34,35]
#   (1.2,1.22]        1       2       3       2
#   (1.22,1.26]       3       1       2       1
#   (1.26,1.28]       1       3       0       1
#   (1.28,1.3]        1       0       2       1

答案 1 :(得分:0)

这是答案:

library(dvmisc)
table(data2[,.(quant_groups(height, 4),(quant_groups(weight, 4)))])

                 V2
V1            [31,32] (32,33] (33,34] (34,35]
  [1.21,1.24]       3       3       2       1
  (1.24,1.27]       5       1       2       1
  (1.27,1.29]       4       2       1       2
  (1.29,1.3]        0       0       2       1