在R语言中处理日期和时间

5

我有一个数据框,有两列,第一列包含日期,第二列包含时间,格式为:

     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. 如何对一天中的时间做相同的操作(每小时的桶足够了)?

谢谢


4
请将文本从英语翻译成中文。仅返回已翻译的文本:无需列出月份名称,请记住 month.namemonth.abb 已经内置,并使用您系统的默认语言。 - J. Win.
2个回答

6

如果您的数据框中除了日期和时间之外还有其他数据,建议使用xts。

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")

看起来很有趣,我会试一试! - nico

4
如果您不介意标签为“01”而不是“January”,您可以像这样操作:
barplot(table(format(df$date,"%m")))

3
好主意。请注意,"%B" 提供完整的月份名称,而 "%b" 则提供缩写。有关所有转换规范,请参见 ?strptime - Joshua Ulrich
好的,我不在意名称,我会隐藏轴并重新编写它们,因为我不需要它们是英文的 :) - nico
1
我不喜欢使用 %B 或 %b 的想法,因为这样会失去月份的自然排序。 - Dason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接