0

I have a table with info on driver infractions and value of infractions. I have two columns Value (of infraction) and year (of infraction). For each year of infraction I have several values. Years go from 2000-2014.

I need a function that can retrieve the total of infractions per a "predetermined" year. I.e., when user types year, only get the info of that year. So far I can only manage to get the info of all years at the same time

I tried this:

total_year <- function(x=infractions$year){
  aggregate(infractions$value ~ infractions$year_deb, FUN=sum, na.rm = TRUE)
}

Then I type

total_year(2012)

and I get a table of infractions per year enlisting all years, but I only want the total for 2012.

My table looks like this:

       value year 
375714  1,00 2011 
375715  0,00 2012 
375716  0,00 2013 
375717  0,00 2014 
375738 12,00 2011 
375739  7,00 2012 
375740  2,00 2013 
375741  4,00 2014 
375762 23,00 2011 
375763 14,00 2012 
375764 18,00 2013 
375765  7,00 2014 
375786  6,00 2011 
375787  4,00 2012 
375788  2,00 2013 
375789  5,00 2014 
375810  0,00 2011 
375811  0,00 2012 
375812  0,00 2013
Uwe
  • 41,420
  • 11
  • 90
  • 134
  • Do you want the total _number_ of infractions from that year? Or a list of the infractions from that year? Also, you'll have more luck getting an answer (and getting one quickly) if you can give a reproducible example (see [here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)) for others to work with – MeetMrMet Feb 08 '17 at 18:21
  • yes, the total number of infractions from that year. Ie: total number of infractions for the year (2012) thanks. I will try to reproduce the example – jessica l Feb 08 '17 at 19:08
  • value year 375714 1,00 2011 375715 0,00 2012 375716 0,00 2013 375717 0,00 2014 375738 12,00 2011 375739 7,00 2012 375740 2,00 2013 375741 4,00 2014 375762 23,00 2011 375763 14,00 2012 375764 18,00 2013 375765 7,00 2014 375786 6,00 2011 375787 4,00 2012 375788 2,00 2013 375789 5,00 2014 375810 0,00 2011 375811 0,00 2012 375812 0,00 2013 – jessica l Feb 08 '17 at 19:20
  • Formatted text and code, moved data from comment into Q, rephrased title – Uwe Feb 09 '17 at 10:39

1 Answers1

0

Here's another solution using dplyr

Data

set.seed(123)

df <- data.frame(value = sample(c("speeding", "parking", "dui"), 45, replace = T),
                 year = rep(2000:2014, 3))

Function

library(dplyr)

total_year <- function(data, x) {
  data %>%
    filter(year == x) %>%
    group_by(year) %>%
    summarize(inf = length(unique(value))) %>%
    ungroup
}

Usage

total_year(df, 2014)
#     year   inf
#     <int> <int>
#   1  2014     1
MeetMrMet
  • 1,349
  • 8
  • 14