R 中意外的应用函数行为 [英] Unexpected apply function behaviour in R
问题描述
我通过 apply
发现了一个令人惊讶的行为,我想知道是否有人可以解释一下.让我们看一个简单的矩阵:
I've discovered a surprising behaviour by apply
that I wonder if anyone can explain. Lets take a simple matrix:
> (m = matrix(1:8,ncol=4))
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
我们可以这样垂直翻转它:
We can flip it vertically thus:
> apply(m, MARGIN=2, rev)
[,1] [,2] [,3] [,4]
[1,] 2 4 6 8
[2,] 1 3 5 7
这将 rev()
向量反转函数迭代地应用于每一列.但是当我们尝试按行应用 rev 时,我们得到:
This applies the rev()
vector reversal function iteratively to each column. But when we try to apply rev by row we get:
> apply(m, MARGIN=1, rev)
[,1] [,2]
[1,] 7 8
[2,] 5 6
[3,] 3 4
[4,] 1 2
...逆时针旋转 90 度!Apply 使用 FUN=function(v) {v[length(v):1]}
提供相同的结果,所以这绝对不是 rev 的错.
.. a 90 degree anti-clockwise rotation! Apply delivers the same result using FUN=function(v) {v[length(v):1]}
so it is definitely not rev's fault.
对此有什么解释吗?
推荐答案
文档指出
如果每次调用 FUN 都返回一个长度为 n 的向量,则 apply 返回一个维度为 c(n, dim(X)[MARGIN]) 如果 n > 1 的数组.
If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1.
从这个角度来看,这种行为无论如何都不是错误,而是它的工作方式.
From that perspective, this behaviour is not a bug whatsoever, that's how it intended to work.
有人可能想知道为什么选择它作为默认设置,而不是保留原始矩阵的结构.考虑以下示例:
One may wonder why this is chosen to be a default setting, instead of preserving the structure of the original matrix. Consider the following example:
> apply(m, 1, quantile)
[,1] [,2]
0% 1.0 2.0
25% 2.5 3.5
50% 4.0 5.0
75% 5.5 6.5
100% 7.0 8.0
> apply(m, 2, quantile)
[,1] [,2] [,3] [,4]
0% 1.00 3.00 5.00 7.00
25% 1.25 3.25 5.25 7.25
50% 1.50 3.50 5.50 7.50
75% 1.75 3.75 5.75 7.75
100% 2.00 4.00 6.00 8.00
> all(rownames(apply(m, 2, quantile)) == rownames(apply(m, 1, quantile)))
[1] TRUE
一致?的确,我们为什么要期待别的?
Consistent? Indeed, why would we expect anything else?
这篇关于R 中意外的应用函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!