Adding non-zero elements of a matrix in R

折月煮酒 提交于 2019-12-12 04:54:54

问题


I have a matrix 'w' with zero and non-zero elements. I want to print out the index of the non-zero elements in the matrix, print the values of each non-zero element and get the sum of the non-zero elements in the matrix. I know I can print the index of non-zero elements using

which(w!=0, arr.ind=TRUE)

I am trying to print the values of the non-zero elements in 'w' matrix but the code is returning the whole matrix instead of only the non-zero elements.

for(i in 1:36){
for(j in 1:36){
    if(w[i,j]!=0){
    print (w);
    }
    }
    }

I want to take out the non-zero elements in 'w' so that I can print the sum.


回答1:


To print the non-zero values:

w[w != 0]

To sum:

sum(w[w !=0 ])

ExperimenteR is of course correct that this will yield the same result as sum(w).



来源:https://stackoverflow.com/questions/28968848/adding-non-zero-elements-of-a-matrix-in-r

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