2011-03-18 44 views
3

我有一个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,但如果答案在那里,我没有看到它。

任何帮助,将不胜感激。

+0

看一看http://stackoverflow.com/questions/1256347/plot-time-data-in-r-to-various-resolutions-to-the-minute-to-the-hour-这对了 – Benjamin 2011-03-18 18:25:12

回答

3

这里有一种方法:

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

+0

美丽!发布后,我想出了一种使用c,subset和mean的方法,但是我必须有一个子集并且意味着每个“bin”的调用。这很容易理解。谢谢! – 2011-03-21 13:35:31

1

您可以通过转换为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")) 
1

Mages' blog上有关于此主题的好帖子。要获得分时段数据:

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

如果你只是想快速图形,ggplot2是你的朋友:

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

不幸的是,因为切返回一个因素,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"), ...) 
相关问题