如何处理矩阵的零元素

时间:2015-04-08 15:18:03

标签: r matrix null elements

我有以下矩阵。

     [,1]      [,2]      [,3]      [,4]
[1,] 0.3421638 0.6578362 0.0000000 0.0000000
[2,] 0.0000000 0.0000000 0.3417066 0.6582934
[3,] 0.6237054 0.3762946 0.0000000 0.0000000
[4,] 0.0000000 0.0000000 0.3567124 0.6432876

我想提取没有null元素的矩阵。

     0         1
[1,] 0.3421638 0.6578362
[2,] 0.3417066 0.6582934
[3,] 0.6237054 0.3762946
[4,] 0.3567124 0.6432876

我如何在代码R中执行此操作?

1 个答案:

答案 0 :(得分:3)

 t(apply(Mat, 1, function(x)x[x!=0]))
          [,1]      [,2]
[1,] 0.3421638 0.6578362
[2,] 0.3417066 0.6582934
[3,] 0.6237054 0.3762946
[4,] 0.3567124 0.6432876