Aggregate (count) rows that match a condition, group by unique values Aggregate (count) rows that match a condition, group by unique values r r

Aggregate (count) rows that match a condition, group by unique values


And here is the data.table solution:

> library(data.table)> dt <- data.table(sessions)> dt[, length(contact[relpos == 0 & maxpos > 1]), by = contactGrp]     contactGrp V1[1,]       west  2[2,]      south  0[3,]       east  0> dt[, length(contact[relpos == 1 & maxpos > 1]), by = contactGrp]     contactGrp V1[1,]       west  1[2,]      south  1[3,]       east  0


I think this is the ddply version you're looking for:

ddply(sessions,.(contactGrp),      summarise,      count = length(contact[relpos == 0 & maxpos > 1]))


Your first attempted line with aggregate doesn't work because there is no function count. You meant length. All you had to do was execute that with conditional data selection for relpos and maxpos, and also select a dummy variable to get the count of (doesn't matter which). Nevertheless, instead of using flexible aggregating commands of various kinds the built in table command is designed just for this.

with( data[data$relpos == 1 & data$maxpos > 1,], table(contactGrp) )