Averaging a sequence in blocks

Problem

You want to chop a sequence of data into blocks of a given length, and find the average of each block. This is one way of smoothing data.

Solution

Suppose you have a numeric vector and want to find the average of the first four numbers, the second four, and so on.

  1. # Generate a vector with 22 random numbers from 0-99
  2. set.seed(123)
  3. x <- floor(runif(22)*100)
  4. x
  5. #> [1] 28 78 40 88 94 4 52 89 55 45 95 45 67 57 10 89 24 4 32 95 88 69
  6. # Round up the length of vector the to the nearest 4
  7. newlength <- ceiling(length(x)/4)*4
  8. newlength
  9. #> [1] 24
  10. # Pad x with NA's up to the new length
  11. x[newlength] <- NA
  12. x
  13. #> [1] 28 78 40 88 94 4 52 89 55 45 95 45 67 57 10 89 24 4 32 95 88 69 NA NA
  14. # Convert to a matrix with 4 rows
  15. x <- matrix(x, nrow=4)
  16. x
  17. #> [,1] [,2] [,3] [,4] [,5] [,6]
  18. #> [1,] 28 94 55 67 24 88
  19. #> [2,] 78 4 45 57 4 69
  20. #> [3,] 40 52 95 10 32 NA
  21. #> [4,] 88 89 45 89 95 NA
  22. # Take the means of the columns, and ignore any NA's
  23. colMeans(x, na.rm=TRUE)
  24. #> [1] 58.50 59.75 60.00 55.75 38.75 78.50