删除包含全零的数组层

时间:2014-08-19 04:25:58

标签: arrays r layer

我正在尝试删除包含全零的数组图层。这是一个例子:

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)]。我看到this question但它只能做一行或一列。有没有办法做整个图层?

谢谢!

1 个答案:

答案 0 :(得分:4)

一个想法,利用apply可以对行(MARGIN = 1),列(MARGIN = 2)层(MARGIN = 3)和更高层的任意组合起作用的事实维度(MARGIN= 4和更高)。

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