How to count cases by group with n() when there are missing data

Viewed 47

I am trying to summarise data with mean and number of cases, without counting missing data. Is it possible to do it with n()? The expected results for N should be 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)
2 Answers

Use complete.cases to get a logical vector of complete/not complete rows, then sum the vector's values by group.

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

You can filter the data upstream before passing to summarise and that will do.

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()

Gives the folowing output.

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