各组因子水平

问题描述

我有一个数据表,如下所示:

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
)

我想将身高分成几组。但是,我希望男女分开。以下代码为我提供了三个因子级别,我希望其中六个因子。

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

我觉得它应该很简单,但是我不知道该怎么写。

所需的输出:

> 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

解决方法

一种data.table解决方案:

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,unique = TRUE)][,paste(Sex,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 
,

这可能是适当的。我们最终不会使用table来显示输出,尽管我仍然认为小标题输出可能更有用:

library(dplyr)

dt %>%
    mutate(Height = cut(Height,166,181,301))) %>%
    group_by(Sex,Height,.drop = FALSE) %>%
    summarise(n = n())

## A tibble: 6 x 3
## Groups:   Sex [2]
#  Sex   Height        n
#  <chr> <fct>     <int>
#1 F     (0,166]       2
#2 F     (166,181]     2
#3 F     (181,301]     0
#4 M     (0,166]       1
#5 M     (166,181]     3
#6 M     (181,301]     0

请注意,breaks参数可以读为“直到这个数字”,因此要获得所需的输出,我们需要在每个整数(即breaks = c(0,301)上加1。如果我们希望空组像您期望的输出一样显示(默认为.drop = FALSE),我们还需要指定TRUE

相关问答

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