Jim Jim - 2 months ago 8
R Question

R: how to assign A[B[, j], j] without for-loop

I want to replace certain values in matrix

A
by another value:
1
in this case. For column j of
A
the row-indices that need to be replaced are those in the jth column of
B
. Below I give an example, where the assignment is achieved by a for-loop.

My question is: how could this assignment be achieved simpler, more efficient and/or without the for-loop?

set.seed(4521)
n <- 10
p <- 5

A <- matrix(rep(NaN,n*p),n,p)

B <- replicate(p, sample(n))
B <- B[1:5,]

for (j in 1:n){
A[B[,j],j] <- 1
}

print(B)
print(A)


B
:

[,1] [,2] [,3] [,4] [,5]
[1,] 5 10 7 6 5
[2,] 10 2 9 9 2
[3,] 7 9 3 10 4
[4,] 9 4 1 3 3
[5,] 4 8 6 4 9


A
:

[,1] [,2] [,3] [,4] [,5]
[1,] NaN NaN 1 NaN NaN
[2,] NaN 1 NaN NaN 1
[3,] NaN NaN 1 1 1
[4,] 1 1 NaN 1 1
[5,] 1 NaN NaN NaN 1
[6,] NaN NaN 1 1 NaN
[7,] 1 NaN 1 NaN NaN
[8,] NaN 1 NaN NaN NaN
[9,] 1 1 1 1 1
[10,] 1 1 NaN 1 NaN

Jim Jim
Answer

Simple solution:

A[cbind(as.numeric(B), as.numeric(col(B)))] <- 1
Comments