本文介绍了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.

对此有任何解释吗?

推荐答案

文档指出

从这个角度来看,此行为绝不是错误,而是它的工作方式.

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中意外的套用功能行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 16:20