How to set a Direction in an user defined function concerning a matrix

rstudio
matrix

#1

Hey guys,

i got this matrix:

>           [,1]       [,2]        [,3]
> [1,]  0.2487505  0.2153659  1.08827780
> [2,]  0.3957978 -0.3829338 -0.69194995
> [3,]  0.6654827  0.4728056  0.08625421
> [4,] -1.3806616 -0.6598443  1.03937054

I defined this function to calculate the means of the second row:

> MeanFunction <- function (Matrix1){return(mean(Matrix1[2,]))}
> MeanFunction (Matrix1)

Now i want to revise the function, so that I can choose in which direction (or dimension) to calculate the means, i.e., the means of rows or the means of columns depending on the input option.
How can I use a conditional construct of my choice inside the function to do that?

Thanks in advance!


#2

Have a look at the apply function (help(apply)).

apply(Matrix1, MARGIN = 1, FUN = mean) #row means
apply(Matrix1, MARGIN = 2, FUN = mean) #column means

You could wrap this into your function, for example

MeanFunction <- function(Matrix1, direction){
# direction: char, one of 'rows' or 'columns'
if(direction = 'rows') marg = 1
if(direction = 'columns') marg = 2
apply(Matrix1,MARGIN = marg, FUN = mean)

If you want to know how apply sets the direction - have a look at the source code for the function (simply type apply into the console). You may be able to decipher how this function does it to help you generalize if needed.

Hope this helps.