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.
# Generate a vector with 22 random numbers from 0-99
set.seed(123)
x <- floor(runif(22)*100)
x
#> [1] 28 78 40 88 94 4 52 89 55 45 95 45 67 57 10 89 24 4 32 95 88 69
# Round up the length of vector the to the nearest 4
newlength <- ceiling(length(x)/4)*4
newlength
#> [1] 24
# Pad x with NA's up to the new length
x[newlength] <- NA
x
#> [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
# Convert to a matrix with 4 rows
x <- matrix(x, nrow=4)
x
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 28 94 55 67 24 88
#> [2,] 78 4 45 57 4 69
#> [3,] 40 52 95 10 32 NA
#> [4,] 88 89 45 89 95 NA
# Take the means of the columns, and ignore any NA's
colMeans(x, na.rm=TRUE)
#> [1] 58.50 59.75 60.00 55.75 38.75 78.50
当前内容版权归 cookbook-r.com 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cookbook-r.com .