简体   繁体   English

我有一个由 0 和 1 组成的 15x15 矩阵。 如何计算整个矩阵中 1 的个数?

[英]I have a 15x15 matrix of 0s and 1s. How do I calculate the number of 1s in the entire matrix?

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 中 1 的所有实例,但我没有从count获得任何值:

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

You can do sum(d1) .你可以做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.请注意, count++不会在 R 中增加count :它是一个 C 或 C++ 运算符,在 R 中不可用。还要尽可能避免在 R 中出现循环。

If you want to count occurrences of the string "1" in a character array: sum(d1 == "1") .如果要计算字符数组中字符串"1"的出现次数: 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.附加建议:既然您已经声明数组包含字符数据,那么在代码中的测试i == 1中混合类型并不是一个好主意。 It should be i == "1" .应该是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.事实上,在 R 中, 1 == "1"是真的,所以它不是真正的错误,但它非常容易出错。

I did something like this我做了这样的事情

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM