I have a matrix that looks like this and want to take the mean of each column and combine them into a new matrix.
> MDA
price X3 X5 X10 X13 X20 X64 X86
[1,] 2.851921 0.19537 2.817065 6.5603 7.37657 2.273753 3.73926 4.08654
[2,] 1.355820 -0.58857 -0.253762 4.3871 3.62105 5.070533 6.03979 3.90909
[3,] -1.830597 1.74915 0.173217 5.5275 3.76552 3.100661 4.92384 3.16864
[4,] 6.535637 4.59728 5.848335 6.8814 10.25615 6.663288 3.87881 8.71351
[5,] 4.666041 -0.49024 2.353359 6.8693 8.86881 9.783803 5.42288 5.88306
[6,] 4.959884 2.09005 2.677156 10.1798 7.68598 5.771700 3.64374 4.89176
[7,] 4.014322 5.29507 0.238004 6.1883 6.52230 5.079508 5.33247 5.73703
...
To do this I've been using the following method (note all of this is done in a loop hence the [x+1]
):
MeanMDA[x+1,] <- c(mean(MDA[,1]),mean(MDA[,2]),mean(MDA[,3]),mean(MDA[,4]),mean(MDA[,5]),
mean(MDA[,6]),mean(MDA[,7]),mean(MDA[,8]))
While this works perfectly, it gets really cumbersome when the number of columns gets large. Sometimes there's over 100 variables and I'll have to go through and edit the code accordingly... Is there another neater way of getting the code to take the mean of each row and combine it into a matrix?