R计算来自不规则每小时数据的每日平均数据

时间:2016-12-26 15:40:43

标签: r

我有一个大型数据集,我正在尝试重新格式化。不幸的是,我无法汇总每日数据。

dataset1_updated<- structure(list(X = 1:5, Time = structure(c(1L, 1L, 2L, 3L, 3L), .Label = c("7/29/11 10:29", "7/29/11 10:30", "7/29/11 10:32"
), class = "factor"), O3 = c(32.032608222367, 32.032608222367, 
32.032608222367, 32.032608222367, 32.032608222367), SO2 = c(2.611, 
2.605, 2.744, 2.767, 2.778), NO = c(0.081, 0.081, 0.081, 0.081, 
0.081), NO2 = c(1.938, 1.912, 1.912, 1.896, 1.863), NOx = c(2.019, 
1.993, 1.993, 1.977, 1.944)), .Names = c("X", "Time", "O3", 
"SO2", "NO", "NO2", "NOx"), row.names = c(NA, 5L), class = "data.frame")

我将数据集转换为xts对象,并应用每日均值函数,结果为&#34; NA&#34;。你能告诉我缺少什么吗?

x <- as.xts(as.POSIXct(dataset1_updated$Time, format="%m/%d/%Y %H:%M"))
x_up<- apply.daily(x, colMeans)
write.csv(as.data.frame(as.matrix(x_up)), file="test")

谢谢,

1 个答案:

答案 0 :(得分:0)

我们需要更改xts语句,因为as.xts仅适用于日期时间类,而不适用于整个数据集

xt1 <- xts(dataset1_updated[-(1:2)], order.by = as.POSIXct(dataset1_updated$Time,
                              format = "%m/%d/%y %H:%M"))
x_up <- apply.daily(xt1, colMeans)
x_up
#                          O3   SO2    NO    NO2    NOx
#2011-07-29 10:32:00 32.03261 2.701 0.081 1.9042 1.9852