-1

I have this csv data

Date                       Kilometer
2015-01-01 15:56:00          1
2015-01-01 17:40:00          2
2015-01-02 14:38:00          4
2015-01-02 14:45:00          3

And would like to group date and sum kilometer like that

Date                       Kilometer
2015-01-01                   3
2015-01-02                   7
  • Did you do any google search? This seems like such a basic question. http://stackoverflow.com/questions/7615922/aggregate-r-sum – Gopala Jun 12 '16 at 01:57

2 Answers2

1

We can use data.table

library(data.table)
library(lubridate)
setDT(df)[, .(Kilometer = sum(Kilometer)) , .(Date=date(Date))]
akrun
  • 874,273
  • 37
  • 540
  • 662
0

This can be done using dplyr and lubridate

library(dplyr)
df %>% group_by(Date = lubridate::date(Date)) %>% summarise(Kilometer=sum(Kilometer)) 


        Date Kilometer
      (date)     (int)
1 2015-01-01         3
2 2015-01-02         7
jalapic
  • 13,792
  • 8
  • 57
  • 87
  • Error in function %<% ? –  Jun 12 '16 at 00:39
  • you have to have the library 'dplyr` loaded - also the function is written `%>%` - note the direction of the '>' – jalapic Jun 12 '16 at 00:40
  • Sorry it is %>%, mistake And will load dplyr now! –  Jun 12 '16 at 00:42
  • Not working , and unfortunately its not even giving any comment back, it just keep loading for ever while its just a mini data frame –  Jun 12 '16 at 00:47
  • do you have both packages - 'dplyr' and 'lubridate' loaded? – jalapic Jun 12 '16 at 00:50
  • Absolutely, downloaded and loaded ! –  Jun 12 '16 at 00:51
  • If all dates are in the same format as above it should work fine. How many rows is the dataframe? – jalapic Jun 12 '16 at 00:53
  • Okay, after waiting for a while it worked :) thanks a lot –  Jun 12 '16 at 00:53
  • @jalapic I've never used lubridate before, but I'm keen to learn more about time series data, since I often come up with issues. Any reason to use lubridate here instead of base as.Date ? Does it do this conversion differently? – rosscova Jun 12 '16 at 02:51
  • `as.Date` is fine but like all programming languages dates can be a pain. The `lubridate` package has a lot of easy to use functions. In this case it actually makes sensible guesses as to the format of the date without one having to specify the exact format for instance. – jalapic Jun 12 '16 at 03:00