【问题标题】:How to select and plot hourly averages from data frame?如何从数据框中选择和绘制每小时平均值?
【发布时间】:2011-07-18 09:18:21
【问题描述】:

我有一个如下所示的 CSV 文件,其中“时间”是 UNIX 时间戳:

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

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

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

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

任何帮助将不胜感激。

【问题讨论】:

标签: r statistics


【解决方案1】:

这是一种方法:

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 信息进行调整。

【讨论】:

  • 漂亮!发布后,我想出了一种使用 c、subset 和 mean 的方法,但我必须对每个“bin”都有一个子集和 mean 调用。这更容易理解。谢谢!
【解决方案2】:

您可以通过转换为POSIXlt 并减去分钟和秒部分来计算每次的小时“bin”。然后,您可以向数据框中添加一个包含小时 bin 标记的新列,如下所示:

date.to.hour <- function (vec)
{
    as.POSIXct(
        sapply(
            vec,
            function (x)
            {
                lt = as.POSIXlt(x)
                x - 60*lt$min - lt$sec
            }),
        tz="GMT",
        origin="1970-01-01")
}

data$hour <- date.to.hour(as.POSIXct(data[,1], origin="1970-01-01"))

【讨论】:

    【解决方案3】:

    Mages' blog 上有一篇关于此主题的好帖子。获取分桶数据:

    aggregate(. ~ cut(time, 'hours'), data, mean)
    

    如果您只想快速绘制图表,ggplot2 是您的朋友:

    qplot(cut(time, "hours"), count, data=data, stat='summary', fun.y='mean')
    

    不幸的是,因为 cut 返回一个因子,x 轴将无法正常工作。您可能想编写自己的、不那么尴尬的时间分桶函数,例如

    timebucket = function(x, bucketsize = 1,
                          units = c("secs", "mins",  "hours", "days", "weeks")) {
      secs = as.numeric(as.difftime(bucketsize, units=units[1]), units="secs")
      structure(floor(as.numeric(x) / secs) * secs, class=c('POSIXt','POSIXct'))
    }
    qplot(timebucket(time, units="hours"), ...)
    

    【讨论】:

      猜你喜欢
      • 2017-11-12
      • 2022-07-05
      • 1970-01-01
      • 2013-02-14
      • 2021-06-26
      • 2016-09-04
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      相关资源
      最近更新 更多