Home > OS >  I have a 15x15 matrix of 0s and 1s. How do I calculate the number of 1s in the entire matrix?
I have a 15x15 matrix of 0s and 1s. How do I calculate the number of 1s in the entire matrix?

Time:03-14

I created a count variable which counts all the instances of 1 in the matrix d1 but I am not getting any value from count:

d1 <- as.matrix(i1) 
count <- 0 
for ( i in d1 ) {
 if ( i == 1 ) 
 count   
} 
count

CodePudding user response:

You can do sum(d1). Note that count does not increment count in R: it's a C or C operator, not available in R. Also avoid loops in R whenever it's possible.

If you want to count occurrences of the string "1" in a character array: sum(d1 == "1").

Additional recommendation: now that you have stated that you array holds character data, it's not a very good idea to mix types in the test i == 1 in your code. It should be i == "1". As a matter of fact, in R, 1 == "1" is true, so it's not really a bug, but it's extremely error prone.

CodePudding user response:

I did something like this

d1<-sum(lengths(regmatches(m1,gregexec("0",m1))))
  • Related