Michael C Kang
Michael C Kang

Reputation: 45

Counting days in month in R

I have data frame in R like this..

cambridgeparking <- read.csv("camparking.csv")

Ticket.Issue.Date   Issue.Time   Location      Violation.Description
January 1, 2014     1:24AM       Green ST      NO PARKING
January 2, 2014     10:45AM      Gore ST       NO STOPPING
January 6, 2014     3:00PM       Franklin ST   HANDICAP RAMP
..                  ..           ..            ..
March 9, 2014       3:29AM       Green ST      NO PARKING
..                  ..           ..            ..
November 10, 2014   9:30PM       Marshall ST   METER PASSED
November 30, 2014   10:20PM      Erie ST       METER PASSED

How do I count every violation occurred on a monthly period, so that It would show me total number of violations in each month?

I have tried to count it by using

janparking <- subset(camparking, Ticket.Issue.Date=="January 1, 2014")

however, it only counts violations occurred during January 1, 2014.

Upvotes: 0

Views: 86

Answers (1)

akrun
akrun

Reputation: 886948

We can extract the month from the 'Ticket.Issue.Date' by removing part of the substring after the month with sub and then use table to get the count per month.

table(sub(' .*', '', camparking$Ticket.Issue.Date))

# January    March November 
#   3        1        2 

If we need only for 'January'

sum(sub(' .*', '', camparking$Ticket.Issue.Date)=='January')
#[1] 3

data

camparking <- structure(list(Ticket.Issue.Date = c("January 1, 2014", 
"January 2, 2014", 
"January 6, 2014", "March 9, 2014", "November 10, 2014", 
"November 30, 2014"
), Issue.Time = c("1:24AM", "10:45AM", "3:00PM", "3:29AM", "9:30PM", 
"10:20PM"), Location = c("Green ST", "Gore ST", "Franklin ST", 
"Green ST", "Marshall ST", "Erie ST"), Violation.Description = c("NO PARKING", 
"NO STOPPING", "HANDICAP RAMP", "NO PARKING", "METER PASSED", 
"METER PASSED")), .Names = c("Ticket.Issue.Date", "Issue.Time", 
"Location", "Violation.Description"), class = "data.frame",
 row.names = c(NA, -6L))

Upvotes: 2

Related Questions