Home > Software engineering >  calculate the average of every 24 values of matrix
calculate the average of every 24 values of matrix

Time:11-24

How can I average a matrix every 24 values? And how can I find the maximum and minimum value for every 24 numbers and compute the maximum minus the minimum?

data <- as.matrix(rnorm(240,8,6)) 

CodePudding user response:

Restructure your matrix to have 24 rows, then compute mean and max-min for each column.

set.seed(13)

data2 <- matrix(data, nrow = 24)

colMeans(data2)
# [1] 9.253395 5.994996 8.587498 6.640410 8.450113 7.471933 6.778594 9.770789
# [9] 7.990745 6.155887

apply(data2, MARGIN = 2, \(x) max(x) - min(x))
# [1] 22.15314 21.84914 16.47159 22.45381 19.81069 22.68133 31.14436 29.72932
# [9] 21.05972 20.37183

CodePudding user response:

Here's one approach using base R.

data <- rnorm(240,8,6), nrow = 24)
colMeans(data) # means
[1] 7.277130 9.168225 9.035287 8.199072 8.586223 6.943131 7.789378 6.325451 8.592744 8.048652

And now to get the maximum minus the minimum

apply(data, 2, function(x) range(x)[2] - range(x)[1]) #range
[1] 20.05621 22.18245 18.00119 22.14814 23.38163 22.66280 31.46512 20.08090 25.93418 17.03183
  • Related