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.