问题
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