Q:

How to use the which function to determine the rows that contain exactly two occurrences of the number 1?

Using the sample.int function to create M as a 6x10 matrix of random integers chosen from {1, 2, ..., 10}, I would like to know how to use the which function to determine the rows that contain exactly 2 occurrences of the number 1.
M <- matrix(sample.int(10, size=6*10, replace=TRUE), nrow = 6, ncol = 10)

I require that the answer be only ONE line of R code (you can call multiple functions in 1 line, of course!).
I tried length(which(M == 1)). That computes the number of elements that match the value 1. My second attempt was to solve the problem using nested for loops, but I was not able to reduce the solution to one line. I do not know if there is an API function call that would simplify things.

A:

We may use
which(rowSums(M == 1) == 2)

M == 1 gives a logical matrix with TRUE where M contains 1, then rowSums gives the number of ones in each row, and which gives the result.

