Frank Terra
Frank Terra

Reputation: 21

Get the correspondence table, with R, grouping each variable in four intervals

I have the following data, and I need to get the correspondence table grouping each variable in four classes or intervals

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

I have the correspondence table, but I need it grouping each variable in four classes

Upvotes: 0

Views: 65

Answers (2)

Frank Terra
Frank Terra

Reputation: 21

This is the answer:

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

Upvotes: 0

DJJ
DJJ

Reputation: 2549

Something like this may be? I use the package data.table and use the first to fourth quantile to set the categories.

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

Upvotes: 1

Related Questions