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)
ok, try this:
library(dplyr)
DT4 %>% as_tibble() %>%
mutate(WatLev = as.numeric(WatLev)) %>%
group_by(Site, Year) %>%
summarise(min = min(WatLev, na.rm = TRUE),
mean = mean(WatLev, na.rm = TRUE),
max = max(WatLev, na.rm = TRUE),
per = sum(WatLev > 0))
output is:
# A tibble: 9 x 6
# Groups: Site [3]
Site Year min mean max per
<chr> <chr> <dbl> <dbl> <dbl> <int>
1 SiteA 2001 -49.8 -24.3 4.76 11
2 SiteA 2002 -50.0 -23.6 4.98 9
3 SiteA 2003 -49.2 -20.7 4.76 16
4 SiteB 2001 -49.3 -21.4 4.85 11
5 SiteB 2002 -49.7 -19.0 4.72 19
6 SiteB 2003 -50.0 -22.0 4.89 17
7 SiteC 2001 -49.2 -20.4 4.97 14
8 SiteC 2002 -49.6 -22.2 4.28 13
9 SiteC 2003 -49.0 -23.3 4.85 14