我希望能够替换矩阵中每行的部分内容为0,但保留指定范围内的内容。每行需要保留的指定范围不同。我可以使用嵌套的for循环来实现此操作。
然而,我认为可能有一种简单的方法,也许可以使用apply语句来实现。
以下是一个使用嵌套for循环解决方案的示例。
然而,我认为可能有一种简单的方法,也许可以使用apply语句来实现。
以下是一个使用嵌套for循环解决方案的示例。
my.matrix <- matrix(c( -5, -4, -3, -2, -1,
-2, -1, 0, 1, 2,
0, 1, 2, 3, 4,
-3, -2, -1, 0, 1), nrow = 4, byrow = TRUE)
# range to retain specified by the following two vectors
first.position <- c(2, 3, 2, 1)
last.position <- c(4, 5, 5, 1)
# desired result
desired.result <- matrix(c( 0, -4, -3, -2, 0,
0, 0, 0, 1, 2,
0, 1, 2, 3, 4,
-3, 0, 0, 0, 0), nrow = nrow(my.matrix), byrow = TRUE)
new.matrix <- matrix(0, nrow = nrow(my.matrix), ncol = ncol(my.matrix))
# solution using loops
for(i in 1:nrow(my.matrix)) {
for(j in 1:ncol(my.matrix)) {
if(j >= first.position[i] & j <= last.position[i]) new.matrix[i,j] = my.matrix[i,j]
}
}
all.equal(new.matrix, desired.result)
# [1] TRUE
n = last.position - first.position + 1; ij = cbind(rep(seq_len(nrow(my.matrix)), n), sequence(n) + rep(first.position, n) - 1); new.matrix = matrix(0, nrow = nrow(my.matrix), ncol = ncol(my.matrix)); new.matrix[ij] = my.matrix[ij]
- alexis_lazm <- t(my.matrix); k <- (seq_along(first.position)-1)*ncol(m); m[-unlist(mapply(seq,first.position+k,last.position+k))] <- 0; result <- t(m)
- Marat Talipov