Chris
Chris

Reputation: 87

R multiple mean by specific range of rows

I have a data.frame/table with

dim(Tn) 
# 43 rows, 30 columns

I am trying to calculate 5-value means (so 39 means per column) for each column, where mean is calculated as

(row-4) : row

like on the picture here:

enter image description here

when running for loop:

test <- for (j in 2:ncol(Tn)){
          for (i in 5:nrow(Tn)){
              mean(Tn[(i-4):i,j])
}   }

I get NULL as result. How to write this loop to get table of 5-value mean for each column for all cases (nrow(Tn)-4) ?

Upvotes: 1

Views: 794

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101403

If you are using base R, you can try with:

data.frame(t(sapply(seq(nrow(Tn)-4), function(v) colMeans(Tn[v:(v+4),-1]))))

which gives you the moving-window average over all columns.

For instance, given input Tn <- data.frame(X = 1:10, Y = 11:20, Z = 21:30):

> Tn
    X  Y  Z
1   1 11 21
2   2 12 22
3   3 13 23
4   4 14 24
5   5 15 25
6   6 16 26
7   7 17 27
8   8 18 28
9   9 19 29
10 10 20 30

then you will get:

   Y  Z
1 13 23
2 14 24
3 15 25
4 16 26
5 17 27
6 18 28

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You need rolling mean which can be calculated using zoo::rollmean. Try

sapply(Tn[-1], zoo::rollmean, k = 5)

Consider this reproducible example, where we calculate 3-value means for 2-columns in df

df <- data.frame(a = 1:5, b = 6:10)
sapply(df, zoo::rollmean, k = 3)

#     a b
#[1,] 2 7
#[2,] 3 8
#[3,] 4 9

Upvotes: 2

Related Questions