R 如何从数据框中选择和绘制小时平均值?

R 如何从数据框中选择和绘制小时平均值?,r,statistics,R,Statistics,我有一个CSV文件,看起来像这样,其中“time”是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=",") d

我有一个CSV文件,看起来像这样,其中“time”是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")

data您可以通过转换为
POSIXlt
并减去分和秒分量来计算每次的小时“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"))
date.to.hour这里有一种方法:

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

上有一篇关于此主题的好文章。要获取带扣数据,请执行以下操作:

aggregate(. ~ cut(time, 'hours'), data, mean)
如果您只想快速绘制图表,您的朋友是:

qplot(cut(time, "hours"), count, data=data, stat='summary', fun.y='mean')
不幸的是,由于cut返回一个因子,x轴将无法正常工作。您可能想编写自己的、不那么麻烦的bucketing函数

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

看看漂亮的!发帖后,我想出了一种使用c、subset和mean的方法,但我必须对每个“bin”都有一个subset和mean调用。这更容易理解。非常感谢。