[英]Shifting matrix by nrow or ncol in R
I need to shift an image (which I have stored as a matrix) up/down or left/right and I would like this to stay within the bounds of the original matrix dimensions. 我需要上下移动图像(已将其存储为矩阵)或向左/向右移动,我希望此图像保持在原始矩阵尺寸的范围内。
To show an example, if I had a 3x3 matrix 举个例子,如果我有一个3x3矩阵
x <- matrix(seq(1,9),3,3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
and I wanted to shift this down one I would get 我想把这个调低
[,1] [,2] [,3]
[1,] NA NA NA
[1,] 1 4 7
[2,] 2 5 8
Could anybody help me with this? 有人可以帮我吗? I would also like the ability to perform this for translations in left/right too
我也希望能够对左右翻译执行此操作
Created a function to deal with 'left', 'right', 'up', 'down'. 创建一个函数来处理“左”,“右”,“上”,“下”。
f1 <- function(mat, dir, n=1){
if(dir %in% c('up', 'down')){
stopifnot(nrow(mat)> n)
i1 <- rep(NA, ncol(mat))
if(dir=='down'){
r1 <- `dimnames<-`(do.call(rbind, c(replicate(n, i1, simplify=FALSE),
list(head(mat, -n)))), NULL)
}
else {
r1 <- `dimnames<-`(do.call(rbind, c(list(tail(mat, -n)),
replicate(n, i1, simplify=FALSE))), NULL)
}
}
else {
stopifnot(ncol(mat) > n)
i2 <- rep(NA, nrow(mat))
if(dir=='right'){
r1 <- `dimnames<-`(do.call(cbind, c(replicate(n, i2, simplify=FALSE),
list(mat[, head(1:ncol(mat),-n)]))), NULL)
}
else {
r1 <- `dimnames<-`(do.call(cbind, c(list(mat[,tail(1:ncol(mat), -n)]),
replicate(n, i2, simplify=FALSE))), NULL)
}
}
r1
}
Checking with different 'n' and the directions. 检查不同的“ n”和方向。
f1(x, 'up', 2)
# [,1] [,2] [,3]
#[1,] 3 6 9
#[2,] NA NA NA
#[3,] NA NA NA
f1(x, 'down',2)
# [,1] [,2] [,3]
#[1,] NA NA NA
#[2,] NA NA NA
#[3,] 1 4 7
f1(x, 'left',1)
# [,1] [,2] [,3]
#[1,] 4 7 NA
#[2,] 5 8 NA
#[3,] 6 9 NA
f1(x, 'right',1)
# [,1] [,2] [,3]
#[1,] NA 1 4
#[2,] NA 2 5
#[3,] NA 3 6
f1(x, 'right',3)
#Error: ncol(mat) > n is not TRUE
f1(x, 'up',3)
#Error: nrow(mat) > n is not TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.