根据其他一些数据移动矩阵行
Shifting rows of matrices depending on some other data
我很抱歉重复了一个关于 *apply 函数的问题,但我无法让我的代码与我目前发现的 material 一起工作。我有一个矩阵(存储在一个大数据框中),我想将这个矩阵的行移动一定量(向左)。我想要移动的量对于每一行都是不同的,并且存储在同一数据框的另一列中。下面的代码应该可以说明我的目标
mat <- matrix(rnorm(15),ncol=5,nrow=3);
sv <- c(1,4,2);
mat;
shift <- function(x,shift){c(x[(1+max(0,shift)):length(x)],rep(0,max(0,shift)))}
for(i in 1:nrow(mat)){mat[i,] <- shift(mat[i,],sv[i])}
mat;
但是这在我的 300000x201 矩阵上运行得非常慢,所以我如何对其进行矢量化(使用一些 *apply 命令)?
处理更大的块会加快速度
n.col <- ncol(mat)
for(i in unique(sv)){
selection <- which(sv == i)
mat[selection, 1:(n.col - i + 1)] <- mat[selection, i:n.col]
mat[selection, (n.col - i + 1):n.col] <- 0
}
我很抱歉重复了一个关于 *apply 函数的问题,但我无法让我的代码与我目前发现的 material 一起工作。我有一个矩阵(存储在一个大数据框中),我想将这个矩阵的行移动一定量(向左)。我想要移动的量对于每一行都是不同的,并且存储在同一数据框的另一列中。下面的代码应该可以说明我的目标
mat <- matrix(rnorm(15),ncol=5,nrow=3);
sv <- c(1,4,2);
mat;
shift <- function(x,shift){c(x[(1+max(0,shift)):length(x)],rep(0,max(0,shift)))}
for(i in 1:nrow(mat)){mat[i,] <- shift(mat[i,],sv[i])}
mat;
但是这在我的 300000x201 矩阵上运行得非常慢,所以我如何对其进行矢量化(使用一些 *apply 命令)?
处理更大的块会加快速度
n.col <- ncol(mat)
for(i in unique(sv)){
selection <- which(sv == i)
mat[selection, 1:(n.col - i + 1)] <- mat[selection, i:n.col]
mat[selection, (n.col - i + 1):n.col] <- 0
}