frc - 1 year ago 89

R Question

Let us have a matrix

`M`

`> M`

[,1] [,2] [,3] [,4]

[1,] 15 0 0 9

[2,] 0 1 8 24

[3,] 4 0 0 0

[4,] 3 2 0 0

[5,] 0 0 56 0

a vector of its column indices

`ind`

`> ind=c(2,4)`

> ind

[1] 2 4

and a value

`x`

`x=0`

`M`

`ind`

`x`

The following code returns proper row indices:

`> which(M[,2]==0 & M[,4]==0)`

[1] 3 5

but I need a solution that will use a vector

`ind`

`> which(M[,ind]==0)`

[1] 1 3 5 8 9 10

but instead I got the entries which have zeros in either of the columns indicated by

`ind`

Answer Source

How about

```
rowSums(M[, ind] == 0) == length(ind)
# [1] FALSE FALSE TRUE FALSE TRUE
```

Let's break the code down step-by-step:

`M[, ind] == 0`

- get a logical matrix showing where`M[, ind]`

is zero`rowSums(.)`

- determine how many TRUE values are in each row`. == length(ind)`

- compare it to the number of columns used

And if you need the numeric indices, wrap it in `which()`

.

```
which(rowSums(M[, ind] == 0) == length(ind))
# [1] 3 5
```

**Data:**

```
M <- structure(c(15L, 0L, 4L, 3L, 0L, 0L, 1L, 0L, 2L, 0L, 0L, 8L,
0L, 0L, 56L, 9L, 24L, 0L, 0L, 0L), .Dim = c(5L, 4L), .Dimnames = list(
NULL, c("V1", "V2", "V3", "V4")))
ind <- c(2, 4)
```