我在R中有一个预分配的矩阵,需要用来自具有以下格式的文件生成的数据帧中的数据填充它:
1-1-7
1-3-2
2-2-6
1-4-8
....
Run Code Online (Sandbox Code Playgroud)
其中第一列包含行索引,第二列包含列索引,第三列包含值.
以下循环是否有更快/更好的方式?
for(i in 1:nrow(file)){
matrix[file[i,1],file[i,2]]=file[i,3]
}
Run Code Online (Sandbox Code Playgroud)
akr*_*run 11
使用row/colindex作为第一列和第二列,file并使用这些索引指定file[,3]to m1.
m1[as.matrix(file[1:2])] <- file[,3]
m1
# [,1] [,2] [,3] [,4]
#[1,] 7 0 2 8
#[2,] 0 6 0 0
Run Code Online (Sandbox Code Playgroud)
如上所述,我们根据行/列索引分配值.如果我们取前两列并转换为矩阵,则第一列充当行索引,第二列充当列索引
as.matrix(file[1:2])
# v1 v2
#[1,] 1 1
#[2,] 1 3
#[3,] 2 2
#[4,] 1 4
Run Code Online (Sandbox Code Playgroud)
如果我们m1基于第一行进行子集化,即1 1,我们得到的行为m1at row = 1和column = 1,类似于第二行,它将是row = 1和column = 3的元素,依此类推.在这里,我们创建了一个0具有指定尺寸的矩阵.因此,基于行/列位置的4个值将是0
m1[as.matrix(file[1:2])]
#[1] 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
现在,我们通过将值分配给'file'的第3列来更改/替换指定行/列位置的'm1'中的值
m1[as.matrix(file[1:2])] <- file[,3]
Run Code Online (Sandbox Code Playgroud)
如果我们检查指定位置的值,它将被替换
m1[as.matrix(file[1:2])]
#[1] 7 2 6 8
Run Code Online (Sandbox Code Playgroud)
或者我们可以使用使用另一种方法sparseMatrix,从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
Run Code Online (Sandbox Code Playgroud)
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]))
Run Code Online (Sandbox Code Playgroud)