How do I count the occurrences of a factor in several columns, grouping by one column?

aggregate, r

Solution

Alternative `plyr` and `data.table` solutions:

data.table:

require(data.table)
tmp.dt <- data.table(temp, key="Job")
tmp.dt[, lapply(.SD, sum), by=Job]

#         Job C.C.. Java Python
# 1: Developer     2    2      1
# 2:   Student     0    2      1
# 3:  Sysadmin     1    0      0

plyr:

require(plyr)
ddply(temp, .(Job), function(x) colSums(x[-1]))

#         Job C.C.. Java Python
# 1 Developer     2    2      1
# 2   Student     0    2      1
# 3  Sysadmin     1    0      0

Edit: If instead of TRUE/FALSE, you've to count the number of `Newbie`'s, then:

With data.table:

require(data.table)
tmp.dt <- data.table(temp, key="Job")
tmp.dt[, lapply(.SD, function(x) sum(x == "Newbie")), by=Job]

With plyr:

require(plyr)
ddply(temp, .(Job), function(x) colSums(x[-1] == "Newbie"))

Problem

I have a seemingly simple question, but I cannot figure out how to get exactly what I want. My data looks like this: ``` Job C/C++ Java Python Student FALSE TRUE FALSE Developer TRUE TRUE TRUE Developer TRUE TRUE FALSE Sysadmin TRUE FALSE FALSE Student FALSE TRUE TRUE ``` I would like to group by the "Job" column and count the number of `TRUE`s in each column. My desired output would look like this: ``` Job C/C++ Java Python Student 0 2 1 Developer 2 2 1 Sysadmin 1 0 0 ``` Any help would be greatly appreciated.

Original source