【发布时间】:2014-04-11 02:53:47
【问题描述】:
这是我在Can I subset specific years and months directly from POSIXct datetimes?提出的问题的后续行动
我有一个数据框
test <- data.frame(seq(from = as.POSIXct("1983-03-09 01:00"), to = as.POSIXct("1985-01-08 00:00"), by = "hour"))
colnames(test) <- "DateTime"
test$Value<-sample(0:100,16104,rep=TRUE)
我正在使用特定年份和月份进行子集化
# Add year column
test$Year <- as.numeric(format(test$DateTime, "%Y"))
# Add month column
test$Month <- as.numeric(format(test$DateTime, "%m"))
# Subset specific year (1984 in this case)
sub1 = subset(test, Year!="1983" & Year!="1985")
# Subset specific months (April and May in this case)
sub2 = subset(test, Month=="4" | Month=="5")
从sub1 和sub2 的这些子集中,我想使用每小时数据来计算Value 列中的每日最小值、平均值和最大值。
我在Aggregating hourly data into daily aggregates找到了解决方案
stat <- function(x) c(min = min(x), max = max(x), mean = mean(x))
sub1$Date <- as.Date(sub1$DateTime)
sub2$Date <- as.Date(sub2$DateTime)
aggregate(Value ~ Date, sub1, stat)
aggregate(Value ~ Date, sub2, stat)
这似乎给出了列中的最小值、平均值和最大值(尽管我无法验证,因为我无法读取 R 输出窗口的顶部)。我需要将这些aggregate 结果转换为包含Date、min、mean 和max 的数据框。有谁知道我该怎么做?我试过了
sub1.sum <- aggregate(Value ~ Date, sub1, stat)
和
sub1.sum <- as.data.frame(aggregate(Value ~ Date, sub1, stat))
但这似乎只返回一个值(我不确定这是最小值、平均值还是最大值)。
【问题讨论】:
-
好的,当我运行你的代码时
aggregate(Value ~ Date, sub1, stat)返回Date Value.min Value.max Value.mean 1 1984-01-01 1.00000 76.00000 41.93750 . .......... ....... ........ ........这不是你想要的。 -
你好 CCurtis,是的,这就是我想要的,但我想将这些结果存储在一个数据框中,其中包含日期、最小值、平均值和最大值列。你知道我该怎么做吗?到目前为止(上图)我的尝试都失败了。
标签: r