I'm trying to create a function which collects the maximum value from multiple time periods of a population and stores them in a sample of maximum values (ie. Block Maxima)
So far I have:
function(pop, n)
{
x <- length(pop)
sample <- numeric(x/n)
j=0
i=0
while(i<x)
{
sample[j] <- max(pop[i:i+n])
j=j+1
i=i+n
}
return(sample)
}
But, I can not figure out the correct way to calculate the maximum. Can anyone help?
You can use dplyr
for that:
library(dplyr)
block_max <- function(pop, n) {
data.frame(pop = pop, group = ceiling(seq_along(pop) / n)) %>%
group_by(group) %>%
summarise(max_group = max(pop))
}
block_max(1:100, 11)