A short post about counting and aggregating in R, because I learned a couple of things while improving the work I did earlier in the year about analyzing reference desk statistics. I’ll post about that soon.
I often want to count things in data frames. For example, let’s say my antimatter equivalent Llib and I have been drinking some repetitive yet oddly priced beverages:
(Note how I specified two names and four drinks, but they repeated themselves to fill up the eight lines to equal the size of the cost sequence I specified. R does that automatically and it’s very useful.)
How many times does each name occur? That’s just basic counting, which is easy with the count
function from Hadley Wickham’s excellent plyr
package. Now, like a lot of R functions, the count
help page is a bit intimidating.
The help page says:
count package:plyr R Documentation
Count the number of occurences.
Description:
Equivalent to ‘as.data.frame(table(x))’, but does not include
combinations with zero counts.
Usage:
count(df, vars = NULL, wt_var = NULL)
...
Hmm! But there are examples at the bottom, and like all R documentation, you can just run then and look at what happens, which will probably explain everything. And here are more. How many times does each name occur?
How many times did each person drink each drink? To say you want to tally things up by more than one column use the c
function to combine things into a vector:
It’s all pretty easy. Just tell count
which data frame you’re using, then which columns you want to tally by, and it does the counting very quickly and efficiently.
How much did I spend in total? How much did I spend on each drink? aggregate
does the job for this kind of figuring.
aggregate package:stats R Documentation
Compute Summary Statistics of Data Subsets
Description:
Splits the data into subsets, computes summary statistics for
each, and returns the result in a convenient form.
Again, there are good examples at the end of the help file. But for my example, first let’s see how much Llib and I have spent on each kind of drink:
That command says “I want to apply the sum function to the cost column while aggregating rows based on unique values in the name and drink columns.”
How much did we each spend total? Forgot about aggregating by drink, and just aggregate by name:
What was the mean price we paid? Change sum
to mean
: