Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with dates and times in R

Tags:

datetime

r

I have a data frame with 2 columns, the first containing dates, and the second containing times, in the format:

     date         time        
[1,] "2003-10-03" "22:32:00"
[2,] "2003-10-05" "17:43:06"
[3,] "2003-10-10" "18:45:56"
[4,] "2003-11-12" "17:07:16"
[5,] "2003-11-13" "12:48:04"
[6,] "2003-11-13" "18:17:57"

I would like to create some histograms of these data looking at the number of events per year, per months and at a specific hour of the day.

For the year that's easy

hist(as.Date(df[,1]), "years")

Now, to get the number of events per months (disregarding the year) I used:

 months = c("January", "February", "March", 
            "April", "May", "June", "July", 
            "August", "September", "October", 
            "November", "December")
 tb <- table(factor(months.Date(dt), levels=months)
 barplot(tb)

Questions:

  1. Is there a nicer way to do the histogram per month?
  2. How do I do the same thing for the time of the day (hourly bins are sufficient)?

Thanks

like image 301
nico Avatar asked Jan 26 '11 19:01

nico


2 Answers

I would use xts, especially if you have data other than dates and times in your data.frame.

df$count <- 1
x <- xts(df$count,as.POSIXct(paste(df$date,df$time)))

# create aggregates and plot with plot.zoo()
plot.zoo(period.apply(x, endpoints(index(x),"years"), sum), type="h")
plot.zoo(period.apply(x, endpoints(index(x),"quarters"), sum), type="h")
plot.zoo(period.apply(x, endpoints(index(x),"months"), sum), type="h")
plot.zoo(period.apply(x, endpoints(index(x),"weeks"), sum), type="h")
plot.zoo(period.apply(x, endpoints(index(x),"days"), sum), type="h")
plot.zoo(period.apply(x, endpoints(index(x),"hours"), sum), type="h")
like image 132
Joshua Ulrich Avatar answered Oct 21 '22 02:10

Joshua Ulrich


If you don't mind the labels being "01" instead of "January" you could do something like this

barplot(table(format(df$date,"%m")))
like image 32
Dason Avatar answered Oct 21 '22 02:10

Dason