Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factor levels by group

I have a data.table that looks as follows:

library(data.table)
dt <- fread(
    "Sex   Height   
     M   180   
     F   179
     F   162   
     M   181  
     M   165   
     M   178   
     F   172   
     F   160",
  header = TRUE
)

I would like to split the height into groups. However, I want separate groups for men and women. The following code gives me three factor level, where I would like six.

dt[,height_f := cut(Height, breaks = c(0, 165, 180, 300), right = FALSE), by="Sex"]

> table(dt$height_f)

  [0,165) [165,180) [180,300) 
        2         4         2

I have the feeling that it should be something very simple, but I cannot figure out how to write it.

Desired output:

> table(dt$height_f)

  M:[0,165) M:[165,180) M:[180,300) F:[0,165) F:[165,180) F:[180,300) 
        0         3          1            2         2         0
like image 677
Tom Avatar asked Feb 15 '26 15:02

Tom


1 Answers

A data.table solution:

dt[, height_cat := cut(Height, breaks = c(0, 165, 180, 300), right = FALSE)]
dt[, height_f := 
       factor(
         paste(Sex, height_cat, sep = ":"), 
         levels = dt[, CJ(Sex, height_cat, unique = TRUE)][, paste(Sex, height_cat, sep = ":")]
       )]

table(dt$height_f)
# F:[0,165) F:[165,180) F:[180,300)   M:[0,165) M:[165,180) M:[180,300) 
#         2           2           0           0           2           2 
like image 139
sindri_baldur Avatar answered Feb 17 '26 06:02

sindri_baldur