使用应用于多维数组 [英] Use apply on a multi-dimension array

查看:128
本文介绍了使用应用于多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

法线矩阵将是二维矩阵.但是,我可以初始化:

A normal matrix would be 2-dimension matrix. But, I can initialise:

a<-array(0,dim=c(2,3,4,5))

哪个是2 * 4 * 5 * 3矩阵或数组.

Which is a 2*4*5*3 matrix, or array.

命令

apply(a,c(2,3),sum)

将给出一个4 * 5数组,其中包含第1维和第4维元素的总和.

will give a 4*5 array, contain the sum over elements in the 1st and 4th dimension.

为什么呢?据我所知,在apply函数中,1表示行,2表示列,但是3在这里是什么意思?

Why it that? As far as I know, in the apply function, 1 indicates rows, 2 indicates columns, but what does 3 mean here?

我们在这里需要一些抽象.

We need some abstraction here.

推荐答案

了解数组上apply的最简单方法是尝试一些示例.这是从最后一个示例对象文档:

The easiest way to understand apply on an array is to try some examples. Here's some data modified from the last example object in the documentation:

> z <- array(1:24, dim = 2:4)
> dim(z)
[1] 2 3 4

> apply(z, 1, function(x) sum(x))
[1] 144 156
> apply(z, 2, function(x) sum(x))
[1]  84 100 116
> apply(z, 3, function(x) sum(x))
[1]  21  57  93 129

这是怎么回事?好吧,我们创建一个三维数组z.如果将applyMARGIN=1一起使用,则会得到行总和(两个值,因为有两行),如果使用MARGIN=2,则会得到列总和(三个值,因为有三列),并且如果使用您将获得数组第三维的总和(四个值,因为数组的第三维有四个级别).

What's going on here? Well, we create a three-dimensional array z. If you use apply with MARGIN=1 you get row sums (two values because there are two rows), if you use MARGIN=2 you get column sums (three values because there are three columns), and if you use MARGIN=3 you get sums across the array's third dimension (four values because there are four levels to the third dimension of the array).

如果为MARGIN指定一个向量,例如c(2,3),则将获得每列的行总和以及第三维的级别.请注意,在上面的示例中,applyMARGIN=1的结果分别是矩阵的行总和和MARGIN=2列的总和,如下所示:

If you specify a vector for MARGIN, like c(2,3) you get the sum of the rows for each column and level of the third dimension. Note how in the above examples, the results from apply with MARGIN=1 are the row sums and with MARGIN=2 the column sums, respectively, of the matrix seen in the result below:

> apply(z, c(2,3), function(x) sum(x))
     [,1] [,2] [,3] [,4]
[1,]    3   15   27   39
[2,]    7   19   31   43
[3,]   11   23   35   47

如果将所有尺寸都指定为MARGIN=c(1,2,3),则只需获得原始的三维对象:

If you specify all of the dimensions as MARGIN=c(1,2,3) you simply get the original three-dimensional object:

> all.equal(z, apply(z, c(1,2,3), function(x) sum(x)))
[1] TRUE

最好的学习方法是开始研究一些真实的矩阵.您的示例数据对求和没有帮助,因为所有数组项均为零.

Best way to learn here is just to start playing around with some real matrices. Your example data aren't helpful for looking at sums because all of the array entries are zero.

这篇关于使用应用于多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆