Search code examples
rtriplet

Convert triplets to matrix in R


I have triplets and want to convert them to the matrix.

This is my code:

data = data.frame(row = c(1,2,3), column = c(2,3,1), value = c(0.1, 0.2, 0.5));
m <- matrix(0, nrow = max(data$row), ncol = max(data$column));
m[ data$row, data$col ] = data$value;

The output is

    [,1] [,2] [,3]
[1,]  0.1  0.1  0.1
[2,]  0.2  0.2  0.2
[3,]  0.5  0.5  0.5

Desire output is

     [,1] [,2] [,3]
[1,]  0    0.1  0
[2,]  0    0    0.2
[3,]  0.5  0    0

How can I do that without loop?


Solution

  • Try

    m[cbind(data[,1], data[,2])] <- data$value
    

    Or

     m[as.matrix(data[1:2])] <- data$value
     m
     #    [,1] [,2] [,3]
     #[1,]  0.0  0.1  0.0
     #[2,]  0.0  0.0  0.2
     #[3,]  0.5  0.0  0.0