【问题标题】:Assign most common value of factor variable with summarize in R使用 R 中的汇总分配因子变量的最常见值
【发布时间】:2022-11-25 10:10:50
【问题描述】:

R 菜鸟,在tidyverse/RStudio 工作。

我有一个分类/因子变量,我想保留在 group_by/summarize 工作流中。我想 summarize 它使用一个汇总函数返回每个组中该因素的最常见值。

我可以为此使用摘要功能吗?

mean 返回 NAmedian 仅适用于数字数据,summary 给我单独的行,其中包含每个因子级别的计数,而不是最常见的级别。

编辑:示例使用mtcars 数据集的子集:

mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear carb 
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <fct>
21       6  160    110  3.9   2.62  16.5     0     1     4 4    
21       6  160    110  3.9   2.88  17.0     0     1     4 4    
22.8     4  108     93  3.85  2.32  18.6     1     1     4 1    
21.4     6  258    110  3.08  3.22  19.4     1     0     3 1    
18.7     8  360    175  3.15  3.44  17.0     0     0     3 2    
18.1     6  225    105  2.76  3.46  20.2     1     0     3 1    
14.3     8  360    245  3.21  3.57  15.8     0     0     3 4    
24.4     4  147.    62  3.69  3.19  20       1     0     4 2    
22.8     4  141.    95  3.92  3.15  22.9     1     0     4 2    
19.2     6  168.   123  3.92  3.44  18.3     1     0     4 4

在这里,我已将 carb 转换为因子变量。在这个数据子集中,您可以看到在 6 缸汽车中,有 3 辆带有carb=4,1 辆带有carb=1;同样,在 4 缸汽车中,有 2 辆带有carb=2,1 辆带有carb=1

所以如果我这样做:

data %>% group_by(cyl) %>% summarise(modalcarb = FUNC(carb))

FUNC 是我正在寻找的功能,我应该得到:

cyl carb 
<dbl> <fct>
4    2    
6    4    
8    2  # there are multiple potential ways of handling multi-modal situations, but that's secondary here   

希望这是有道理的!

【问题讨论】:

  • 您可以使用Modedf1 %&gt;% group_by(yourgroup) %&gt;% summarise(Mode = Mode(yourcolumn))
  • 您能否提供一个带有预期输出的最小示例?
  • @akrun 是否有一个内置函数可以做到这一点?
  • 不确定是否有任何软件包具有此功能。

标签: r dplyr tidyverse summarize


【解决方案1】:

您可以使用collapse 的函数fmode 来计算模式。在这里,我使用 mtcars 数据集创建了一个可重现的示例,其中 cyl 列是您要分组的因子变量,如下所示:

library(dplyr)
library(collapse)

mtcars %>%
  mutate(cyl = as.factor(cyl)) %>%
  group_by(cyl) %>%
  summarise(mode = fmode(am))
#> # A tibble: 3 × 2
#>   cyl    mode
#>   <fct> <dbl>
#> 1 4         1
#> 2 6         0
#> 3 8         0

创建于 2022-11-24 reprex v2.0.2

【讨论】:

    【解决方案2】:

    我们可以在count之后使用which.max

    library(dplyr)
    
    # fake dataset
    x <- mtcars %>% 
      mutate(cyl = factor(cyl)) %>% 
      select(cyl) 
    
    x %>% 
      count(cyl) %>% 
      slice(which.max(n))
    
      cyl       n
      <fct> <int>
    1 8        14
    

    【讨论】:

      【解决方案3】:

      您可以使用which.max 进行索引,使用table 进行计数。

      library(tidyverse)
      
      mtcars |>
        group_by(cyl) |>
        summarise(modalcarb = carb[which.max(table(carb))])
      #> # A tibble: 3 x 2
      #>     cyl modalcarb
      #>   <dbl>     <dbl>
      #> 1     4         2
      #> 2     6         4
      #> 3     8         3
      

      【讨论】:

        猜你喜欢
        • 2017-04-24
        • 2018-11-27
        • 1970-01-01
        • 1970-01-01
        • 2021-01-04
        • 2018-04-01
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多