-1

I have 25 time series of monthly returns of different portfolios as columns (S1B1, S1B2, S1B3, S1B4, S1B5, S2B1, S2B2, S2B3, S2B4, S2B5, (...), S5B5):

S1B1 S1B2 S1B3 S1B4 S1B5 (...) S5B5   
0.2  0.1  2.1  3.2  1.2        0.3
0.3  1.2  2.6  2.1  6.3        0.2
0.5  0.5  0.5  2.2  6.2        1.2
0.4  1.2  2.2  1.1  0.5        2.1

I want to create a 5x5 matrix showing means for every column in the following way:

S1B1 S1B2 S1B3 S1B4 S1B5    
S2B1 S2B2 S2B3 S2B4 S2B5   
S3B1 S3B2 S3B3 S3B4 S3B5   
S4B1 S4B2 S4B3 S4B4 S4B5   
S5B1 S5B2 S5B3 S5B4 S5B5
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166

3 Answers3

1

You can use the apply function to calculate the mean for every column.

You can use it this way :

apply(M, 2, mean) # where M is your data (presumably a matrix or a data frame)

And then put each result in an entry in your matrix.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Gherbi Hicham
  • 2,416
  • 4
  • 26
  • 41
1

The obvious solution here is to use the vectorized colMeans function (as apply being a for loop, is becoming inefficient as the data set grows). Try this

matrix(colMeans(M), ncol = 5, byrow = TRUE)
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
0

It's very simple. First, you should calculate mean for each column, then you should reshape resulting 1x25 vector into 5x5 matrix:

matrix(apply(data,2,mean), nrow=5, ncol=5, byrow=TRUE)

apply(data,2,mean) calculates mean values for each column of data and matrix constructs a 5x5 matrix from its results.

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122