Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tidyr how to spread into count of occurrence [duplicate]

Have a data frame like this

other=data.frame(name=c("a","b","a","c","d"),result=c("Y","N","Y","Y","N"))

How can I use spread function in tidyr or other function to get the count of result Y or N as column header like this

name       Y   N
a          2   0
b          0   1

Thanks

like image 997
santoku Avatar asked May 21 '16 14:05

santoku


2 Answers

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
like image 196
Gopala Avatar answered Nov 02 '22 16:11

Gopala


Here is another option using dcast from data.table

library(data.table)
dcast(setDT(other), name~result, length)
#    name N Y
#1:    a 0 2
#2:    b 1 0
#3:    c 0 1
#4:    d 1 0

Although, table(other) would be a compact option (from @mtoto's comments), for large datasets, it may be more efficient to use dcast. Some benchmarks are given below

set.seed(24)
other1 <- data.frame(name = sample(letters, 1e6, replace=TRUE), 
    result = sample(c("Y", "N"), 1e6, replace=TRUE), stringsAsFactors=FALSE)

other2 <- copy(other1)

gopala1 <- function() other1 %>% 
                          group_by(name) %>%
                          summarise(N = sum(result == 'N'), Y = sum(result == 'Y'))
gopala2 <- function() spread(as.data.frame(table(other1)), result, Freq)
gopala3 <- function() spread(count(other1, name, result), result, n, fill = 0)
akrun <- function() dcast(as.data.table(other2), name~result, length)


library(microbenchmark)
microbenchmark(gopala1(), gopala2(), gopala3(),
                    akrun(), unit='relative', times = 20L)
#      expr      min       lq     mean   median       uq      max neval
# gopala1() 2.710561 2.331915 2.142183 2.325167 2.134399 1.513725    20
# gopala2() 2.859464 2.564126 2.531130 2.683804 2.720833 1.982760    20
# gopala3() 2.345062 2.076400 1.953136 2.027599 1.882079 1.947759    20
#   akrun() 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000    20
like image 5
akrun Avatar answered Nov 02 '22 15:11

akrun