plyr - Count occurrences of factor in R, with zero counts reported -
i want count number of occurrences of factor in data frame. example, count number of events of given type in code below:
library(plyr) events <- data.frame(type = c('a', 'a', 'b'), quantity = c(1, 2, 1)) ddply(events, .(type), summarise, quantity = sum(quantity))
the output following:
type quantity 1 3 2 b 1
however, if know there 3 types of events a
, b
, c
, , want see count c
0
? in other words, want output be:
type quantity 1 3 2 b 1 3 c 0
how do this? feels there should function defined somewhere.
the following 2 not-so-good ideas how go this.
idea #1: know using for
loop, know said if using for
loop in r
, doing wrong, there must better way it.
idea #2: add dummy entries original data frame. solution works feels there should more elegant solution.
events <- data.frame(type = c('a', 'a', 'b'), quantity = c(1, 2, 1)) events <- rbind(events, data.frame(type = 'c', quantity = 0)) ddply(events, .(type), summarise, quantity = sum(quantity))
you free if define events
variable correctly factor desired 3 levels:
r> events <- data.frame(type = factor(c('a', 'a', 'b'), c('a','b','c')), + quantity = c(1, 2, 1)) r> events type quantity 1 1 2 2 3 b 1 r> table(events$type) b c 2 1 0 r>
simply calling table()
on factor right thing, , ddply()
can if tell not drop
:
r> ddply(events, .(type), summarise, quantity = sum(quantity), .drop=false) type quantity 1 3 2 b 1 3 c 0 r>
Comments
Post a Comment