Reputation: 647
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?
Upvotes: 3
Views: 79
Reputation: 48191
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
Upvotes: 5
Reputation: 9618
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
Upvotes: 2