繁体   English   中英

处理R中的日期和时间

[英]Dealing with dates and times in R

我有一个包含2列的数据框,第一列包含日期,第二列包含时间,格式如下:

     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"

我想创建一些这些数据的直方图,查看每年,每月和每天特定时段的事件数量。

这一年很容易

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

现在,为了获得每个月的事件数量(无视年份),我使用了:

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

问题:

  1. 有没有更好的方法每月做直方图?
  2. 我如何在一天中的时间做同样的事情(每小时箱就足够了)?

谢谢

我会使用xts,特别是如果你的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")

如果你不介意标签是“01”而不是“1月”你可以做这样的事情

barplot(table(format(df$date,"%m")))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM