【问题标题】:How to count cases by group with n() when there are missing data缺少数据时如何使用 n() 按组计数案例
【发布时间】:2020-12-16 13:00:44
【问题描述】:

我正在尝试summarise 具有平均值和案例数量的数据,而不计算丢失的数据。 n()可以做到吗? N 的预期结果应该是3, 2

library(tidyverse)

df <- tibble(g = c(1, 1, 1, 2, 2, 2), x = c(1, 2, 3, 4, NA, 5))

df %>%
  group_by(g) %>%
  summarise(M = mean(x, na.rm = TRUE),
            N = n()) %>%
  ungroup()
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 2 x 3
#>       g     M     N
#>   <dbl> <dbl> <int>
#> 1     1   2       3
#> 2     2   4.5     3
Created on 2020-12-16 by the reprex package (v0.3.0)

【问题讨论】:

  • 不,n() 不可能,因为它给出了当前组大小,而不管其他变量是否有缺失值。您可以将非 NA 案例的数量相加。
  • 我尝试了这些但没有成功:count = sum(!is.na(.)), sum = sum(.,na.rm=TRUE))

标签: r tidyverse


【解决方案1】:

使用complete.cases 获取完整/不完整行的逻辑向量,然后按组使用sum 向量的值。

df %>%
  mutate(N = complete.cases(.)) %>%
  group_by(g) %>%
  summarise(M = mean(x, na.rm = TRUE),
            N = sum(N), .groups = 'drop') %>%
  ungroup()
## A tibble: 2 x 3
#      g     M     N
#  <dbl> <dbl> <int>
#1     1   2       3
#2     2   4.5     2

【讨论】:

  • 如果我在 df 中有另一列,例如 y = c(NA, NA, 1, 2, 3, 4),结果将是错误的。我不得不将complete.cases(.) 更改为complete.cases(x)
【解决方案2】:

您可以在传递到汇总之前过滤上游数据,这样就可以了。

library(tidyverse)

df <- tibble(g = c(1, 1, 1, 2, 2, 2), x = c(1, 2, 3, 4, NA, 5))

Answer <- df %>%
  na.omit() %>%
  group_by(g) %>%
  summarise(M = mean(x),
            N = n()) %>%
  ungroup()

给出以下输出。

# A tibble: 2 x 3
      g     M     N
  <dbl> <dbl> <int>
1     1   2       3
2     2   4.5     2

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多