eclipse
eclipse

Reputation: 3021

R index matrix with vector / create index matrix from index vector

I am looking for an easier way to do the following:

m <- matrix(0, nrow=3, 3) 
v <- c(1, 3, 2)

for (i in 1:nrow(m)) {
  m[[i, v[i]]] = 1
}

The above code creates the following index matrix:

      [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    0    1
[3,]    0    1    0

There surely must be a better way to do this?!

Upvotes: 2

Views: 67

Answers (1)

josliber
josliber

Reputation: 44340

One way to do it without pre-defining the matrix would be to use outer:

num.col <- 3
outer(v, seq_len(num.col), "==") * 1
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    0    1
# [3,]    0    1    0

Upvotes: 2

Related Questions