0

I have a data frame item_sold_time with a item_sold_time$SaleDate "POSIXct" "POSIXt" column, looking like this 2015-04-28 07:59:43.

I want to aggregate by month in year:

df2<-aggregate(list(Qty=item_sold_time$Qty), by=list(ISBN=item_sold_time$ISBN,DateYM=strftime(item_sold_time$SaleDate, format="%Y-%b")), FUN=sum)

The problem with strftime is that it converts the date into characters and I get an error if I try to convert it back into date.

I tried all combinations of date formatting, I could find in 2 days of searching. The final destination of that date is to be used in this plot:

ggplot(df2, aes(x = DateYM, y=Qty))

Please help. Thanks

adlisval
  • 341
  • 1
  • 7
  • 17
  • date have year, month and day and not just year and month. – akrun Oct 07 '16 at 14:06
  • Ok, so no way to get it as date. But is there a way to aggregate by Year,Month only and still be able to order it as a date would be ordered (2013-jun before 2013-jul before 2014-mar)? – adlisval Oct 07 '16 at 14:14
  • The package **zoo** has support for actual year-month columns, which can be useful. – joran Oct 07 '16 at 14:16
  • Thank you @joran , I'll have look. – adlisval Oct 07 '16 at 14:18
  • [Here](http://stackoverflow.com/questions/6242955/converting-year-and-month-yyyy-mm-format-to-a-date-in-r) is an example of using `zoo::as.yearmon()` to format month-year data as a date. Then `scale_x_yearmon` should help with the plotting in [ggplot2](http://stackoverflow.com/questions/22968702/modifying-plot-in-ggplot2-using-as-yearmon-from-zoo). – aosmith Oct 07 '16 at 15:06

1 Answers1

0

Set each date to (e.g.) the 15th of the month, then can aggregate by date and plot as normal.

as.Date(format(item_sold_time$SaleDate, "%Y-%m-15"))
Richard Telford
  • 9,558
  • 6
  • 38
  • 51