Remove layer of array that contains all zeros

喜夏-厌秋 提交于 2019-12-06 07:23:57

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!