Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 数组R的圆移位_Arrays_R - Fatal编程技术网

Arrays 数组R的圆移位

Arrays 数组R的圆移位,arrays,r,Arrays,R,我试图在R中循环移位一个N维数组。下面是一个例子,来自移动2D矩阵的pracma包a: if (is.matrix(a) && length(sz) == 2) { n <- nrow(a); m <- ncol(a) s1 <- sz[1] %% n s2 <- sz[2] %% m a <- a[(1:n-s1-1) %% n + 1, (1:m-s2-1) %% m + 1] } if(is.矩阵(a)&&le

我试图在R中循环移位一个N维数组。下面是一个例子,来自移动2D矩阵的
pracma
a

if (is.matrix(a) && length(sz) == 2) {
    n <- nrow(a); m <- ncol(a)
    s1 <- sz[1] %% n
    s2 <- sz[2] %% m
    a <- a[(1:n-s1-1) %% n + 1, (1:m-s2-1) %% m + 1]
}
if(is.矩阵(a)&&length(sz)==2){

n您可以通过以下方法完成此操作:

# using map2 from purrr for simplicity, though you could also use lapply
library(purrr)

circshift_any <- function(a, sz) {
  indexers <- map2(dim(a), sz, function(len, s) (1:len - s - 1) %% len + 1)
  indexing_matrix <- as.matrix(do.call(expand.grid, indexers))

  array(a[indexing_matrix], dim(a))
}
# using map2 from purrr for simplicity, though you could also use lapply
library(purrr)

circshift_any <- function(a, sz) {
  indexers <- map2(dim(a), sz, function(len, s) (1:len - s - 1) %% len + 1)
  indexing_matrix <- as.matrix(do.call(expand.grid, indexers))

  array(a[indexing_matrix], dim(a))
}
a <- array(1:100, c(5, 20))

identical(pracma::circshift(a, c(3, 6)), circshift_any(a, c(3, 6)))
identical(pracma::circshift(a, c(23, 19)), circshift_any(a, c(23, 19)))