gpt4 book ai didi

r - 使用 R 聚合数据

转载 作者:行者123 更新时间:2023-12-01 11:55:44 27 4
gpt4 key购买 nike

我正在尝试通过读取我的 CSV 文件来使用 R 绘制数据,该文件包含一些每秒记录的值。我希望 R 以每分钟为基础聚合数据,以便我可以使用 plot(TIME,VALUE.) 绘制每分钟数据。我的 CSV 文件包含类似这样的内容;

Store No.,Date,Time,Watt
33,2011/09/26,09:11:01,0.0599E+03
34,2011/09/26,09:11:02,0.0597E+03
35,2011/09/26,09:11:03,0.0598E+03
36,2011/09/26,09:11:04,0.0596E+03
37,2011/09/26,09:11:05,0.0593E+03
38,2011/09/26,09:11:06,0.0595E+03
39,2011/09/26,09:11:07,0.0595E+03
40,2011/09/26,09:11:08,0.0595E+03
41,2011/09/26,09:11:09,0.0591E+03

由于我是 R 的新手,因此无法按分钟汇总时间和瓦特列。非常感谢任何帮助。

最佳答案

假设商店编号无关紧要,并将问题中显示的示例数据的最后三行更改为 09:12:.. 而不是 09:11:.. 所以我们至少有两分钟:

# create test data

Lines <- "Store No.,Date,Time,Watt
33,2011/09/26,09:11:01,0.0599E+03
34,2011/09/26,09:11:02,0.0597E+03
35,2011/09/26,09:11:03,0.0598E+03
36,2011/09/26,09:11:04,0.0596E+03
37,2011/09/26,09:11:05,0.0593E+03
38,2011/09/26,09:11:06,0.0595E+03
39,2011/09/26,09:12:07,0.0595E+03
40,2011/09/26,09:12:08,0.0595E+03
41,2011/09/26,09:12:09,0.0591E+03"
cat(Lines, "\n", file = "data.txt")

# read in aggregating at the same time

library(zoo)
library(chron)
z <- read.zoo("data.txt", header = TRUE, sep = ",", index = 2:3,
FUN = paste, FUN2 = function(x) trunc(as.chron(x), "00:01:00"),
aggregate = mean)[, -1]

此处 FUN 应用于 index 指定的列。它将它们粘贴在一起,然后将 FUN2 应用于 FUN 创建 chron 日期/时间的结果。最后,具有相同 FUN2 值的行然后采用 Watt 的平均值进行聚合,给出:

> z
(09/26/11 09:11:00) (09/26/11 09:12:00)
59.63333 59.36667

根据需要,aggregate 参数可以更改为 aggregate = function(x) tail(x, 1) 代替 aggregate 参数显示。

有关更多信息和示例,请加载 zoo 包并查看 ?read.zoo?aggregate.zoovignette("zoo-read") 以及其他小插图和帮助文件。

更新:通过使用 FUN2 参数略微简化。不确定,但 read.zoo 参数首次回答此问题时可能不存在。

关于r - 使用 R 聚合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7556008/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com