This is kind of a follow-up to my question at Can I subset specific years and months directly from POSIXct datetimes?
I have a dataframe
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)
and I am subsetting particular years and months using
# 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")
From these subsets sub1
and sub2
, I want to use the hourly data to calculate daily minimum, mean, and maximum from column Value
.
I found a solution at 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)
This appears to give the minimum, mean, and maximum in columns (although I can't verify as I can't read the top in the R output window). I need to make these aggregate
results into a dataframe containing Date
, min
, mean
, and max
. Does anyone know how I might do that? I've tried
sub1.sum <- aggregate(Value ~ Date, sub1, stat)
and
sub1.sum <- as.data.frame(aggregate(Value ~ Date, sub1, stat))
but that appears to just return a single value (i'm not sure if this is the min, mean, or max).