简体   繁体   中英

ddply summarise on multiple variables

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

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

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM