Ushuaia81
Ushuaia81

Reputation: 564

Assign value matrix based on index condition

How can I assign a value into a matrix based in a vector condition index. A working example is:

# Input: 
r <- c(2, 1, 3)
m <- matrix(rep(0, 9), nrow = 3)

# Desired output
result <- matrix(c(0, 1, 0,
               1, 0, 0,
               0, 1, 0), nrow = 3)
result.

# I try with this notation but it does not work:
sapply(1:3, function(x)m[x, r[x]] <- 1)

Upvotes: 1

Views: 172

Answers (1)

akrun
akrun

Reputation: 887048

We use row/column indexing to assign

m[cbind(seq_len(nrow(m)), r)]  <- 1

Or using replace

replace(m, cbind(seq_len(nrow(m)), r), 1)

Upvotes: 1

Related Questions