[英]Apply a bunch of functions to columns of a matrix in R
There is a way to apply a function f
to every column of a matrix: 有一种方法可以将函数
f
应用于矩阵的每一列:
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. 但是如果我想建立一个关于矩阵的描述性统计数据,我应该使用更多的indeces。 For example,
max, min, mean
etc. 例如,
max, min, mean
等。
But R doesn't allow to do something like this: 但R不允许做这样的事情:
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? 你能告诉我如何处理这个问题吗?
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.