Count rows with same dates

I have the following variable:

     datevote 
1   1981-6-21
2   1981-6-21
3   1981-9-23
4   1982-2-14
5   1982-2-14

and so on...

What I'd like to have in the end is a new column in which the number of the same dates of column "datevote" ist displayed:

  datevote        numbervotes
1   1981-6-21     2
2   1981-6-21     2
3   1981-9-23     1
4   1982-2-14     2
5   1982-2-14     2

I have tried several things, but it seems more work than expected. Can anyone help me? All the help is appreciated, thanks.

Answers


You can use the new dplyr package like this.

library(dplyr)
df <- data.frame(datevote = as.Date(c("1981-06-21", "1981-06-21", "1981-06-23", "1981-06-14", "1981-06-14")))

mutate(group_by(df, datevote), numbervotes = n(datevote))
##     datevote numbervotes
## 1 1981-06-21           2
## 2 1981-06-21           2
## 3 1981-06-23           1
## 4 1981-06-14           2
## 5 1981-06-14           2

The equivalent plyr solution is :

detach(package:dplyr)
library(plyr)
ddply(df, "datevote", mutate, numbervotes = length(datevote))

Data.table alternative:

df <- data.frame(datevote = as.Date(c("1981-06-21", "1981-06-21", "1981-06-23", "1981-06-14", "1981-06-14")))
library(data.table)
df <- data.table(df)
df[,numbervotes:=.N, by=datevote]
df

Need Your Help

java.lang.NullPointerException Google Maps Android API V2

android api nullpointerexception maps

I would like to begin by saying I know this error has been posted about 2,000 times, but after looking through pages and pages of people with the same issue and trying all of their fixes, none of t...

How to get ClientID for control generated for a BoundField in ASP.NET?

asp.net forms clientid boundfield

I have a form with BoundFields in it and I need to get ClientID(s) for control(s) associated with each BoundField I have in the form.