Jere - 7 months ago 36

R Question

After several hours of searching, I am turning to your expertise. Beginner in R, I try to speed up my code. My goal is to replace the values in a matrix

`A`

`B`

`B[, 1]`

`i`

`A`

`B[, 2]`

`A`

The first version of my code was to use the match function in a loop.

`for(k in 1:L){`

i <- B[k,1]

j <- B[k,2]

d <- match(i,rownames(A))

e <- match(j,colnames(A))

A[d, e] <- 0

}

The second version allowed me to speed a little bit:

`for( k in 1:L) {`

A[match(B[k,1],rownames(A)), match(B[k,2],colnames(A))] <- 0

}

However, the processing time is long, too long. So I thought to use the

`apply`

`apply`

`B`

Is Using

`apply`

Answer

It appears to me that you can simply do `A[B[, 1:2]] <- 0`

, by using the power of matrix indexing.

For example, `A[cbind(1:4, 1:4)] <- 0`

will replace `A[1,1]`

, `A[2,2]`

, `A[3,3]`

and `A[4,4]`

to 0. In fact, if `A`

has "dimnames" attributes (the "rownames" and "colnames" you refer to), we can also use the character strings as index.

**Reproducible example**

```
A <- matrix(1:16, 4, 4, dimnames = list(letters[1:4], LETTERS[1:4]))
# A B C D
#a 1 5 9 13
#b 2 6 10 14
#c 3 7 11 15
#d 4 8 12 16
set.seed(0); B <- cbind(sample(letters[1:4])), sample(LETTERS[1:4]))
# [,1] [,2]
#[1,] "d" "D"
#[2,] "a" "A"
#[3,] "c" "B"
#[4,] "b" "C"
## since `B` has just 2 columns, we can use `B` rather than `B[, 1:2]`
A[B] <- 0
# A B C D
#a 0 5 9 13
#b 2 6 0 14
#c 3 0 11 15
#d 4 8 12 0
```