将三元组转换为 R 中的矩阵
Convert triplets to matrix in R
我有三胞胎,想将它们转换为矩阵。
这是我的代码:
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
我怎样才能不循环地做到这一点?
尝试
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
另一个选项:
# 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
我有三胞胎,想将它们转换为矩阵。
这是我的代码:
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
我怎样才能不循环地做到这一点?
尝试
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
另一个选项:
# 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