我可以在因子变量上拆分 describe() 吗?

Can I split describe() on a factor variable?

我想根据一个因子变量中的所有值来描述一个响应变量。

我想运行像这样的代码

library("Hmisc")
describe(mtcars$hp)

除了我想通过 cyl

的每个值获得不同的输出

你在找

lapply(split(mtcars,mtcars$cyl),describe)

编辑: 我看到您专门在 hp 上寻找 describe。您可以将 $hp 添加到上述拆分中,或者更简单地使用

tapply(mtcars$hp,mtcars$cyl,describe)

一个tidy/purrr解决方案

library(Hmisc)
library(purrr)
mtcars %>%
  split(.$cyl) %>%
  purrr::map(~ describe(.x$hp))
#> $`4`
#> .x$hp 
#>        n  missing distinct     Info     Mean      Gmd      .05      .10 
#>       11        0       10    0.995    82.64    24.51     57.0     62.0 
#>      .25      .50      .75      .90      .95 
#>     65.5     91.0     96.0    109.0    111.0 
#> 
#> lowest :  52  62  65  66  91, highest:  93  95  97 109 113
#>                                                                       
#> Value         52    62    65    66    91    93    95    97   109   113
#> Frequency      1     1     1     2     1     1     1     1     1     1
#> Proportion 0.091 0.091 0.091 0.182 0.091 0.091 0.091 0.091 0.091 0.091
#> 
#> $`6`
#> .x$hp 
#>        n  missing distinct     Info     Mean      Gmd 
#>        7        0        4    0.911    122.3    23.71 
#>                                   
#> Value        105   110   123   175
#> Frequency      1     3     2     1
#> Proportion 0.143 0.429 0.286 0.143
#> 
#> $`8`
#> .x$hp 
#>        n  missing distinct     Info     Mean      Gmd 
#>       14        0        9    0.985    209.2    56.69 
#> 
#> lowest : 150 175 180 205 215, highest: 215 230 245 264 335
#>                                                                 
#> Value        150   175   180   205   215   230   245   264   335
#> Frequency      2     2     3     1     1     1     2     1     1
#> Proportion 0.143 0.143 0.214 0.071 0.071 0.071 0.143 0.071 0.071

您可以 group_by cyl 并将 describe 对象存储在列表中:

library(dplyr)
library(Hmisc)

new_mtcars <- mtcars %>% group_by(cyl) %>% summarise(data = list(describe(hp)))
new_mtcars
# A tibble: 3 x 2
#    cyl data      
#  <dbl> <list>    
#1     4 <describe>
#2     6 <describe>
#3     8 <describe>

new_mtcars$data[[1]]
#hp 
#       n  missing distinct     Info     Mean      Gmd      .05      .10 
#      11        0       10    0.995    82.64    24.51     57.0     62.0 
#     .25      .50      .75      .90      .95 
#    65.5     91.0     96.0    109.0    111.0 

#lowest :  52  62  65  66  91, highest:  93  95  97 109 113
                                                                  
#Value         52    62    65    66    91    93    95    97   109   113
#Frequency      1     1     1     2     1     1     1     1     1     1
#Proportion 0.091 0.091 0.091 0.182 0.091 0.091 0.091 0.091 0.091 0.091