【问题标题】:Shifting rows of matrices depending on some other data根据其他一些数据移动矩阵行
【发布时间】:2016-07-04 23:32:47
【问题描述】:

我很抱歉重复了一个关于 *apply 函数的问题,但我无法让我的代码与迄今为止找到的材料一起使用。我有一个矩阵(存储在一个大数据框中),我想将该矩阵的行移动一定量(向左)。我想要移动的量对于每一行都不同,并且存储在同一数据帧的另一列中。以下代码应该说明我的目标

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 命令)?

【问题讨论】:

  • 如果你的变量共享同一个类,考虑使用matrix而不是data.frame,会快很多。另外,避免使用相同名称的函数和参数(移位)通常是个好主意。
  • 好的,谢谢提示

标签: r matrix vectorization apply mapply


【解决方案1】:

处理更大的块会加快速度

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
}

【讨论】:

  • 不错的解决方案!循环的第二行不应该是: mat4[selection, 1:(n.col - i)]
猜你喜欢
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多