R: How to take the min and max or other functions of every n rows

Viewed 3375

I have a dataframe of which I put one variable into a vector.

From this vector, I would like to calculate for every 5 values mean, min and max value.

I have managed to calculate the means in this way:

means <- colMeans(matrix(df$values, nrow=5))

I know I can calculate the min and max like this:

max <- max(df$values[1:5])
min <- min(df$values[1:5])

How do I repeat this for every five values?

Edit:

Aditionally, how can I get statistic and p-value from a 1-sample t-test for each n-row?

4 Answers

For those who love dplyr and want to preserve the structure of the data, you can use the RcppRoll package

 df <- data.frame(
   Time = 1:10,
   Value = sample(100:200, 10)
 )

> df
   Time Value
#1     1   122
#2     2   185
#3     3   138
#4     4   134
#5     5   167
#6     6   197
#7     7   161
#8     8   171
#9     9   152
#10   10   106

Now finding the max

df%>%mutate(
   ad = RcppRoll::roll_maxr(Value, 3, fill = "0")
 )
   Time Value  ad
#1     1   122   0
#2     2   185   0
#3     3   138 185
#4     4   134 185
#5     5   167 167
#6     6   197 197
#7     7   161 197
#8     8   171 197
#9     9   152 171
#10   10   106 171
Related