[英]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)
問題:
謝謝
我會使用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.