Christopher Costello
Christopher Costello

Reputation: 1266

R - Aggregate by outcome

I have a tibble like so:

tibble(
  type = c("A", "B", "A", "A", "B", "B", "B"),
  place = c(1, 1, 1, 1, 1, 2, 2)
)

How can I aggregate it to get a tibble like so:

tibble(
  place = c(1, 2),
  n_A = c(3, 0),
  n_B = c(2, 2)
)

Upvotes: 1

Views: 55

Answers (2)

BENY
BENY

Reputation: 323366

You can using table

table(df1$place,df1$type)

    A B
  1 3 2
  2 0 2

Upvotes: 1

neilfws
neilfws

Reputation: 33802

A tidyverse way. Don't really need to include B in replace_na for this example since we know there are no B = NA.

library(dplyr)
library(tidyr)

df1 <- tibble(type = c("A", "B", "A", "A", "B", "B", "B"),
              place = c(1, 1, 1, 1, 1, 2, 2))

df1 %>% 
  group_by(place, type) %>% 
  summarise(n = n()) %>% 
  spread(type, n) %>% 
  replace_na(list(A = 0, B = 0)) %>% 
  rename(n_A = A, n_B = B)

# A tibble: 2 x 3
  place   n_A   n_B
  <dbl> <dbl> <dbl>
1    1.    3.    2.
2    2.    0.    2.

Upvotes: 1

Related Questions