I have a data.frame where I want to calculate min, mean and max and period (number of months with positive values) from annual data for each plot nested in each year and each site. I am trying to use nested loops and the aggregate function to do this but keep encountering errors.
This is what I have tried so far
DT5 <- NULL
for(i in levels(DT4$Site)) {
for(j in levels(DT4$Year)) {
tmp <- subset(subset(DT4, Site == i), Year== j)
min <- aggregate(tmp[,5], list(tmp$Plot), min)
mean <- aggregate(tmp[,5], list(tmp$Plot), mean)
max <- aggregate(tmp[,5], list(tmp$Plot), max)
per <- sum(tmp[,5] > 0)
tmp <- cbind(rep(i, nrow(mean)), rep(j, nrow(mean)), tmp$Year, mean)
}
if(is.null(DT5)){DT5<-tmp} else {DT5<-rbind(DT5,tmp)}
}
where DT4 is a data.frame with columns Site, Year, Month, Plot and WatLev
Ultimately, I want to achieve a data.frame with columns Site, Year, Plot, min, mean, max and per calculated for each plot, in each Site for each year.
Here is an example data set:
Site <- rep(rep(c("SiteA", "SiteB", "SiteC"), each=144),times=3)
Year <- rep(rep(2001:2003, each=48),times=3)
Month <- rep(rep(rep(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), each=4), times=3),3)
Plot <- rep(rep(c("A", "B", "C", "D"), times=36),3)
WatLev <- runif(1296, -50, 5)
DT4 <- cbind(Site, Year, Month, Plot, WatLev)
dplyr(eg withgroup_by()andsummarise()). If you can provide some sample data of yourDT4, we can give you some hands on solutions. - Stephan