将三元组转换为R中的矩阵

时间:2015-02-13 11:33:46

标签: r triplet

我有三胞胎,想把它们转换成矩阵。

这是我的代码:

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;

输出

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

欲望输出

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

如果没有循环我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

尝试

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

或者

 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

答案 1 :(得分:2)

另一种选择:

# just in case your data are not ordered by row value, order them:
data<-data[order(data$row),]

# directly create your matrix by replacing "by default" 0 with data$value in the right positions:
m <- matrix(replace(rep(0, max(data$column)*max(data$row)), data$col+(0:(max(data$row)-1))*max(data$row), data$value), 
            nrow=max(data$row), ncol=max(data$column), byrow=T)

> 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