I created a 6 x 10 matrix of random integers. I need to determine the rows that contain exactly 2 occurrences of the number 1 using which function.
Asked
Active
Viewed 396 times
-1
-
1It's easier to help you if you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data. Why the requirement that `which()` must be used? Do you want to return the row indexes that match? What exactly is the desired output? – MrFlick Sep 07 '16 at 02:03
-
3`which(rowSums(mat == 1) == 2)` – alistaire Sep 07 '16 at 02:04
-
And `which` isn't even needed if you're just doing a subset `mat[rowSums(mat == 1) == 2,]` will be good enough. – thelatemail Sep 07 '16 at 02:06
1 Answers
1
A sample matrix:
set.seed(47)
mat <- matrix(rpois(60, 2), 6, 10)
mat
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 5 1 1 0 3 3 1 2 1 0
## [2,] 1 2 2 2 1 1 5 4 3 2
## [3,] 3 2 2 1 0 2 2 1 1 0
## [4,] 3 4 4 2 0 1 3 1 3 0
## [5,] 2 1 1 2 2 4 0 2 0 2
## [6,] 3 3 0 0 3 2 1 5 0 2
Now
- test which elements are equal to 1 (
mat == 1
), - take the
rowSums
to count theTRUE
s, - test which sums equal 2, and
- use
which
to get the indices
so
which(rowSums(mat == 1) == 2)
## [1] 4 5

alistaire
- 42,459
- 4
- 77
- 117