Home > database >  Calculate mean of every nth element
Calculate mean of every nth element

Time:04-26

I have a vector that holds hourly data of 31 days, so it has a length of 31*24 = 744. Now I would like to calculate the mean diurnal cycle of the variable that is included in the vector. In order to do that, the mean value of every hour of the day is needed. For 01 UTC for example, the relevant steps are 1,25,49,73,...,721, for 2 UTC they are 2,26,50,74,...,722 and so forth. So I need something that enables the calculation of the mean value with a 24 element moving window.

Here is some code for an exemplary vector:

set.seed(1)
my.vec <- sample(-20:20, size = 744, replace = T)

The output vector should then be of length 24, of course.

Anybody with a hint?

CodePudding user response:

Another possible solution, using base R:

rowMeans(matrix(my.vec, 24, 31))

#>  [1] -0.9354839 -0.3548387 -1.0322581  2.5161290  2.1290323  0.7419355
#>  [7]  1.3870968  1.4838710  0.9032258 -1.9032258  4.2903226 -0.4193548
#> [13] -1.9354839 -3.1935484 -2.1935484  2.0322581  0.2580645  2.4193548
#> [19]  0.8064516  0.8064516  5.0645161 -0.5806452 -1.2580645 -0.1290323

CodePudding user response:

base

set.seed(1)
my.vec <- sample(-20:20, size = 744, replace = T)
m <- matrix(my.vec, 31, byrow = TRUE)
colMeans(m)
#>  [1] -0.9354839 -0.3548387 -1.0322581  2.5161290  2.1290323  0.7419355
#>  [7]  1.3870968  1.4838710  0.9032258 -1.9032258  4.2903226 -0.4193548
#> [13] -1.9354839 -3.1935484 -2.1935484  2.0322581  0.2580645  2.4193548
#> [19]  0.8064516  0.8064516  5.0645161 -0.5806452 -1.2580645 -0.1290323

Created on 2022-04-25 by the reprex package (v2.0.1)

CodePudding user response:

We can use rollapply and it should also work with vectors of different lengths

library(zoo)
out <- colMeans(rollapply(seq_along(my.vec), width = 24, by = 24,
     FUN = function(i) my.vec[i]))

-checking

> length(out)
[1] 24
> mean(my.vec[seq(1, length(my.vec), by = 24)])
[1] -0.9354839
> mean(my.vec[seq(2, length(my.vec), by = 24)])
[1] -0.3548387
> out[1:2]
[1] -0.9354839 -0.3548387
  •  Tags:  
  • r
  • Related