1
votes

I see that ddply summarises and groups by variables nicely. I want ddply to scan a very large dataframe only once and provide me a count (length) for more than one variable. How can this be done? For eg:

inc <- c('inc123', 'inc332', 'inc231', 'inc492', 'inc872', 'inc983')
hw <- c('ss23', 'ss43', 'ss98', 'ss98', 'ss23', 'ss23')
app <- c('lkl', 'dsd', 'lkl', 'jhj', 'lkl', 'dsd')
srvc <- c('rr', 'oo', 'rr', 'qq', 'qq', 'pp')

df <- data.frame(inc, hw, app, srvc)
ddply(df, .(hw), summarise, count = length(inc))

The above will give me the count for the number of unique hw's. If I do

ddply(df, .(hw, app, srvc), summarise, count = length(inc))

my objective is lost- because ddply takes every "unique" combination of hw, app, srvc and counts those.

Is there a way to get the count of all the 3 variables in one-shot? Expect the resulting df to be something like this: (might have diff number of rows).

    hw count
1 ss23     3
2 ss43     1
3 ss98     2

    app count
1   dsd     2
2   jhj     1
3 linux     1
4   lkl     2

  srvc count
1   oo     1
2   pp     1
3   qq     2
4   rr     2
2
it doesn't seem compatible with the split-and-apply strategy of plyr: you're asking to split the data.frame in 11 groups that are not disjoint.baptiste
I see that now. use of 'unique' also requires me to run it once for each variable.user1717931

2 Answers

8
votes

You can use plyr::count for that

require(plyr)
llply(c("hw", "app", "srvc"), function(col) count(df, vars = col))
## [[1]]
##     hw freq
## 1 ss23    3
## 2 ss43    1
## 3 ss98    2

## [[2]]
##   app freq
## 1 dsd    2
## 2 jhj    1
## 3 lkl    3

## [[3]]
##   srvc freq
## 1   oo    1
## 2   pp    1
## 3   qq    2
## 4   rr    2
1
votes

I don't know what plyr does internally, but data.table is only going to use the columns that are in the expression itself, effectively scanning the data only once (column by column):

library(data.table)
dt = data.table(df)

lapply(c('hw', 'app', 'srvc'), function(name) dt[, .N, by = name])