dward4 dward4 - 3 years ago 62
R Question

How do I count total items in a column based off of both ID and date without using a for loop?

I have a column of dates [6-13 6-13 7-13 ...], IDs, [1 27 34 555 ...] and a column of 1's and 2's which represent an event on that day. I am trying to count, for each date given and each ID given, the total number of 1 and twos (or just the total number of days that match day and ID). In another language we might write something similar to the below psuedo-code:

For ID in IDs
For Date in Dates
*count the number of days where ID == ID and Date == Date*

How can I do this without a loop?

Answer Source

We can do this with dplyr

df1 %>%
   count(date, ID, anotherCol)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download