我有一维和二维数组。对于一维数组,我想要一个非零元素的计数,非零元素的索引,以及返回没有零的相同数组的好方法:
即:
c(0, 0.09017892, 0, 0, 0, 0, 0.01685147, -0.06063455, 0, 0, 0, 0)
为:
c(0.09017892, 0.01685147, -0.06063455)
同样,对于带有零的二维数组,我想返回一个没有零的二维数组:
即
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[2,] 0 1.00000000 0 0 0 0 -0.09929266 0.1169883 0 0 0 0
[3,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[4,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[5,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[6,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[7,] 0 -0.09929266 0 0 0 0 1.00000000 0.5697163 0 0 0 0
[8,] 0 0.11698827 0 0 0 0 0.56971626 1.0000000 0 0 0 0
[9,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[10,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[11,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
[12,] 0 0.00000000 0 0 0 0 0.00000000 0.0000000 0 0 0 0
为:
[,1] [,2] [,3]
[1,] 1.00000000 -0.09929266 0.1169883
[2,] -0.09929266 1.00000000 0.5697163
[3,] 0.11698827 0.56971626 1.0000000
答案 0 :(得分:2)
提取非零元素:
x[x!=0]
获取指数:
which(x!=0)
获取非零元素的数量:
sum(x!=0)
二维array
案件尚不清楚。如果行和列的某些元素同时具有零和非零元素,会发生什么?但是,在您的示例中:
x[rowSums(x!=0)>0,colSums(x!=0)>0]
# [,1] [,2] [,3]
#[1,] 1.00000000 -0.09929266 0.1169883
#[2,] -0.09929266 1.00000000 0.5697163
#[3,] 0.11698827 0.56971626 1.0000000