如何从数据框中选择和绘制每小时平均值? [英] How to select and plot hourly averages from data frame?

查看:33
本文介绍了如何从数据框中选择和绘制每小时平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 CSV 文件,其中时间"是一个 UNIX 时间戳:

I have a CSV file that looks like this, where "time" is a UNIX timestamp:

time,count
1300162432,5
1299849832,0
1300006132,1
1300245532,4
1299932932,1
1300089232,1
1299776632,9
1299703432,14
... and so on

我正在将它读入 R 并将时间列转换为 POSIXct,如下所示:

I am reading it into R and converting the time column into POSIXct like so:

data <- read.csv(file="data.csv",head=TRUE,sep=",")
data[,1] <- as.POSIXct(data[,1], origin="1970-01-01")

到目前为止很好,但现在我想构建一个直方图,每个 bin 对应于平均小时计数.我坚持按小时选择然后计数.我已经浏览了 ?POSIXt?cut.POSIXt,但如果答案在那里,我没有看到它.

Great so far, but now I would like to build a histogram with each bin corresponding to the average hourly count. I'm stuck on selecting by hour and then counting. I've looked through ?POSIXt and ?cut.POSIXt, but if the answer is in there, I am not seeing it.

任何帮助将不胜感激.

推荐答案

这是一种方法:

R> lines <- "time,count
1300162432,5
1299849832,0
1300006132,1
1300245532,4
1299932932,1
1300089232,1
1299776632,9
1299703432,14"
R> con <- textConnection(lines); df <- read.csv(con); close(con)
R> df$time <- as.POSIXct(df$time, origin="1970-01-01")
R> df$hour <- as.POSIXlt(df$time)$hour
R> df
                 time count hour
1 2011-03-15 05:13:52     5    5
2 2011-03-11 13:23:52     0   13
3 2011-03-13 09:48:52     1    9
4 2011-03-16 04:18:52     4    4
5 2011-03-12 12:28:52     1   12
6 2011-03-14 08:53:52     1    8
7 2011-03-10 17:03:52     9   17
8 2011-03-09 20:43:52    14   20
R> tapply(df$count, df$hour, FUN=mean)
 4  5  8  9 12 13 17 20 
 4  5  1  1  1  0  9 14 
R> 

您的数据实际上还没有一天中每小时有多个条目,但这会在几个小时内取平均值,从 POSIX 时间戳正确解析.您可以根据需要使用 TZ 信息进行调整.

Your data doesn't actually yet have multiple entries per hour-of-the-day but this would average over the hours, properly parsed from the POSIX time stamps. You can adjust with TZ info as needed.

这篇关于如何从数据框中选择和绘制每小时平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆