Pages

Wednesday 25 February 2015

Count Occurrences of Factor in R

events <- data.frame(type = factor(c('A', 'A', 'B'), c('A','B','C')), quantity = c(1, 2, 1))

# Method 1
table(events$type)

# Method 2
xtabs(quantity~type, events)

# Method 3
aggregate(quantity~type, events, FUN=sum)

# Method 4
library(plyr)
ddply(events, .(type), summarise, quantity = sum(quantity), .drop=FALSE)


No comments:

Post a Comment