Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a bunch of functions to columns of a matrix in R

Tags:

r

matrix

apply

There is a way to apply a function f to every column of a matrix:

M <- matrix(seq(1,16), 4, 4)
apply(M, 2, mean)
#[1]  2.5  6.5 10.5 14.5

But if I want to build a descriptive statistics about matrix I should use more indeces. For example, max, min, mean etc.

But R doesn't allow to do something like this:

apply(M, 2, c(mean, max))

to get this output:

#      [,1] [,2] [,3] [,4]
#mean   2.5  6.5 10.5 14.5
#max      4    8   12   16

Would you tell me how to manage with this problem?

like image 768
Macaronnos Avatar asked Nov 29 '25 01:11

Macaronnos


2 Answers

apply(M, 2, function(x) c(mean(x), max(x)))
#      [,1] [,2] [,3] [,4]
# [1,]  2.5  6.5 10.5 14.5
# [2,]  4.0  8.0 12.0 16.0
like image 66
Julius Vainora Avatar answered Nov 30 '25 16:11

Julius Vainora


Try the following:

f <- c("max", "min", "mean")
sapply(f, function(x) apply(M, 2, x))
     max min mean
[1,]   4   1  2.5
[2,]   8   5  6.5
[3,]  12   9 10.5
[4,]  16  13 14.5
like image 22
DatamineR Avatar answered Nov 30 '25 15:11

DatamineR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!