我在R中有一个预先分配的矩阵,需要用从具有以下格式的文件生成的数据填充它:
1-1-7
1-3-2
2-2-6
1-4-8
....其中第一列包含行索引,第二列包含列索引,第三列包含值。
有比下面的循环更快/更好的方法吗?
for(i in 1:nrow(file)){
matrix[file[i,1],file[i,2]]=file[i,3]
}发布于 2015-06-28 11:56:06
使用row/col索引作为file的第一列和第二列,并使用这些索引将file[,3]分配给m1。
m1[as.matrix(file[1:2])] <- file[,3]
m1
# [,1] [,2] [,3] [,4]
#[1,] 7 0 2 8
#[2,] 0 6 0 0正如我前面提到的,我们根据行/列索引分配值。如果将前两列转换为矩阵,则第一列用作行索引,第二列用作列索引。
as.matrix(file[1:2])
# v1 v2
#[1,] 1 1
#[2,] 1 3
#[3,] 2 2
#[4,] 1 4如果我们根据第一行即m1子集,即1 1,我们在row=1和column=1上得到m1的元素,同样对于第2行,它将是row=1和column=3的元素,等等。在这里,我们创建了一个具有指定维度的0矩阵。因此,基于行/列位置的4个值将是0
m1[as.matrix(file[1:2])]
#[1] 0 0 0 0现在,我们在指定的行/列位置上更改/替换“m1”中的值,将该值赋值给“file”的第三列。
m1[as.matrix(file[1:2])] <- file[,3]如果我们检查指定位置的值,它将被替换。
m1[as.matrix(file[1:2])]
#[1] 7 2 6 8或者我们可以使用来自library(Matrix)的另一种使用library(Matrix)的方法
library(Matrix)
sM <- sparseMatrix(file[,1], file[,2], x=file[,3])
as.matrix(sM)
# [,1] [,2] [,3] [,4]
#[1,] 7 0 2 8
#[2,] 0 6 0 0数据
file <- structure(list(v1 = c(1L, 1L, 2L, 1L), v2 = c(1L, 3L, 2L, 4L),
v3 = c(7, 2, 6, 8)), .Names = c("v1", "v2", "v3"),
class = "data.frame", row.names = c(NA, -4L))
m1 <- matrix(0, nrow=max(file[,1]), ncol=max(file[,2]))https://stackoverflow.com/questions/31099477
复制相似问题