Tidyr how to spread into count of occurrence [duplicate]

These are a few ways of many to go about it:

1) With library dplyr, you can simply group things and count into the format needed:

library(dplyr)
other %>% group_by(name) %>% summarise(N = sum(result == 'N'), Y = sum(result == 'Y'))
Source: local data frame [4 x 3]

    name     N     Y
  <fctr> <int> <int>
1      a     0     2
2      b     1     0
3      c     0     1
4      d     1     0

2) You can use a combination of table and tidyr spread as follows:

library(tidyr)
spread(as.data.frame(table(other)), result, Freq)
  name N Y
1    a 0 2
2    b 1 0
3    c 0 1
4    d 1 0

3) You can use a combination of dplyr and tidyr to do as follows:

library(dplyr)
library(tidyr)
spread(count(other, name, result), result, n, fill = 0)
Source: local data frame [4 x 3]
Groups: name [4]

    name     N     Y
  <fctr> <dbl> <dbl>
1      a     0     2
2      b     1     0
3      c     0     1
4      d     1     0

Leave a Comment