2

我有三胞胎,想将它们转换为矩阵。

这是我的代码:

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

没有循环我怎么能做到这一点?

4

2 回答 2

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
于 2015-02-13T11:41:40.767 回答
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
于 2015-02-13T11:58:42.240 回答