Home > Net >  Compute Mean for Specific Row Sequence in R
Compute Mean for Specific Row Sequence in R

Time:04-16

I have the following R code:

n = 10
t = 5
N = n * t

x <- rnorm(N)

I want to calculate the mean for every t observations. That is:

mean(x[1:5])
mean(x[6:10])
.
.
mean(x[46:50])

Similarly,

mean(x[c(1,11,21,31,41)])
mean(x[c(2,12,22,32,42)])
.
.
mean(x[c(10,20,30,40,50)])

How can I do that in a simple way?

Your help is appreciated.

CodePudding user response:

The idea is to go through all records with sapply, with each iteration with an interval of t.

sapply(seq(1, length(x), t), function(i) mean(x[i:(i   t - 1)]))

[1] -0.75555799 -0.17886981 -0.59832657  0.20791804  0.38302358
[6]  0.03449934  0.15240788 -0.17924312 -0.47540067 -0.01974705

For your second condition, we can do similar thing, but the seq would be in mean to better accommodate your need.

sapply(1:n, function(i) mean(x[c(i, (seq(n, N - n, n)   i))]))

[1] -0.251136073  0.641306302 -0.137445178 -0.775326110 -0.771252712
[6] -0.255764112 -0.005568864 -0.089227014  0.415172573 -0.200055188

Data

set.seed(12)

n = 10
t = 5
N = n * t

x <- rnorm(N)
x
 [1] -1.48056759  1.57716947 -0.95674448 -0.92000525 -1.99764210
 [6] -0.27229604 -0.31534871 -0.62825524 -0.10646388  0.42801480
[11] -0.77771958 -1.29388230 -0.77956651  0.01195176 -0.15241624
[16] -0.70346425  1.18887916  0.34051227  0.50696817 -0.29330515
[21]  0.22364142  2.00720146  1.01197912 -0.30245925 -1.02524484
[26] -0.26738483 -0.19910566  0.13112260  0.14579990  0.36206472
[31]  0.67398116  2.07203577 -0.54102865 -1.07049216 -0.37245673
[36] -0.48514135  0.27478418 -0.47951256  0.79810533 -1.00445120
[41]  0.10498423 -1.15599289  0.57813463 -1.59562566 -0.30850366
[46]  0.44946592 -0.97705328  0.18999786  0.73145336 -0.49259911

CodePudding user response:

Using dplyr, create a grouping variable, group by the variable, then find the mean of each group.

data.frame(x = rnorm(N), grp = rep(1:n, each = t)) %>%
    group_by(grp) %>%
    summarise(Mean = mean(x))
  •  Tags:  
  • r
  • Related