按时间聚合

时间:2011-09-11 17:54:12

标签: r time aggregate

我希望针对作为字符串读入的Time列进行聚合,然后对输出进行子集,但我无法将输出tmp$Time转换为Time值。

通过读取csv文件创建数据。

> head(Data)
                 Time  F   Z
1 2011-09-09-06.54.00  1 489
2 2011-09-09-06.54.00  3 678
3 2011-09-09-06.54.00  6 890
4 2011-09-09-07.54.00  8 345
5 2011-09-09-07.54.00 10 567

> strptime(Data$Time, format="%Y-%m-%d-%H.%M.%S" )
[1] "2011-09-09 06:54:00" "2011-09-09 06:54:00"
[3] "2011-09-09 06:54:00" "2011-09-09 07:54:00"
[5] "2011-09-09 07:54:00"

> tmp <- aggregate(Data$Z ~ Data$Time,Data, sum)

> head(tmp)
            Data$Time Data$Z
1 2011-09-09-06.54.00   2057
2 2011-09-09-07.54.00    912

> strptime(tmp[1], format="%Y-%m-%d-%H.%M.%S" )
Data$Time 
       NA 

我在转换它之前使用聚合时间值,因为当它是时间时,我无法让它与Time一起工作。

1 个答案:

答案 0 :(得分:2)

这似乎有效

Data <- data.frame(Time = c("2011-09-09 06:54:00", "2011-09-09 06:54:00",
                            "2011-09-09 06:54:00", "2011-09-09 07:54:00",
                            "2011-09-09 07:54:00"),
                   F = c(1, 3, 6, 8, 10),
                   Z = c(489, 678, 890, 345, 567)   )
tmp <- aggregate(Data$Z ~ Data$Time,Data, sum)

strptime(tmp[,1], format="%Y-%m-%d %H:%M:%S" )

生产

[1] "2011-09-09 06:54:00" "2011-09-09 07:54:00"

我对你的最后一行做了两处修改:

  • tmp[,1]而不是tmp[1]
  • format="%Y-%m-%d %H:%M:%S"而不是format="%Y-%m-%d-%H.%M.%S"