删除包含全零的数组层 [英] Remove layer of array that contains all zeros
本文介绍了删除包含全零的数组层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试删除包含全零的数组的一层.这是一个示例:
I'm trying to remove a layer of an array that contains all zeros. Here's an example:
ii = c(25, 9, 0, 6, 19, 30, 13, 27, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 15, 7, 0, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 43, 33, 40, 34, 42)
key = array(ii,dim=c(3,3,5))
最终结果将等同于key[,,-c(2,4)]
或key[,,c(1,3,5)]
.我看到了这个问题,但它只能做一行或一列.有没有办法做整个图层?
The end result would be equivalent to key[,,-c(2,4)]
or key[,,c(1,3,5)]
. I saw this question but it can only do one row or column. Is there a way to do an entire layer?
谢谢!
推荐答案
使用apply
可以处理行(MARGIN = 1
),列(MARGIN = 2
)层的任意组合这一事实, MARGIN = 3
)和更大的尺寸(MARGIN= 4
和更大).
One idea, making use of the fact that apply
can work on any combination of rows (MARGIN = 1
), columns (MARGIN = 2
) strata (MARGIN = 3
) and higher dimensions as well (MARGIN= 4
and greater).
key[,,!apply(key,3,function(x) all(x == 0) )]
#or more simply:
key[,,apply(key,3,function(x) any(x != 0) )]
#or simpler again:
key[,,apply(key != 0, 3, any)]
#, , 1
#
# [,1] [,2] [,3]
#[1,] 25 6 13
#[2,] 9 19 27
#[3,] 0 30 4
#
#, , 2
#
# [,1] [,2] [,3]
#[1,] 1 0 0
#[2,] 0 15 18
#[3,] 0 7 16
#
#, , 3
#
# [,1] [,2] [,3]
#[1,] 0 0 40
#[2,] 0 43 34
#[3,] 39 33 42
这篇关于删除包含全零的数组层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文