R 如何使用m*(n-i)维矩阵对n维数组进行切片?
如果我有一个n维数组,它可以被这样的m*n矩阵分割R 如何使用m*(n-i)维矩阵对n维数组进行切片?,r,slice,R,Slice,如果我有一个n维数组,它可以被这样的m*n矩阵分割 a <- array(1:27,c(3,3,3)) b <- matrix(rep(1:3,3),3) # This will return the index a[1,1,1] a[2,2,2] and a[3,3,3] a[b] # Output [1] 1 14 27 a我认为这是最干净的方法——制作一个单独的函数: slicem <- function(a,idx,drop=FALSE) do.call(`[
a <- array(1:27,c(3,3,3))
b <- matrix(rep(1:3,3),3)
# This will return the index a[1,1,1] a[2,2,2] and a[3,3,3]
a[b]
# Output
[1] 1 14 27
a我认为这是最干净的方法——制作一个单独的函数:
slicem <- function(a,idx,drop=FALSE) do.call(`[`,c(list(a),idx,list(drop=drop)))
# usage for OP's example
a <- array(1:27, c(3,3,3))
idx <- list(1:2, TRUE, 1:2)
slicem(a,idx)
您必须为未选择的每个维度编写TRUE
根据OP的新期望
如果要将其返回到某种数组中,可以在事后执行:
matrix( nistfun(a, idx), max(lengths(idx)), dim(a)[sapply(idx,isTRUE)]), byrow=TRUE)
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 11 14 17
很抱歉收回接受作为答案,但我意识到您的函数返回两个向量的笛卡尔乘积的索引。理想的结果(如问题中所述)应该是[,1][,2][,3][1,]1 4 7[2,]11 1417@nist我真的不明白你在说什么。在问题中,您说所需的输出是a[c(1,2),,c(1,2)]
,这与我这里的内容相同……还是我误解了?你在评论中给出的数字在问题的任何地方都没有出现…很抱歉误解了。问题是切片创建所有可能的向量组合,我希望向量中的第一个元素成对,然后所有元素在第二个位置,依此类推。该函数必须适用于高维数组和多自由度数组dimensions@nist当存在多个自由维度时,我真的认为你没有考虑到预期的行为。一旦你有了新问题,也许你应该发布一个新问题。新问题发布在这里:希望它更容易理解
slicem <- function(a,idx,drop=FALSE) do.call(`[`,c(list(a),idx,list(drop=drop)))
# usage for OP's example
a <- array(1:27, c(3,3,3))
idx <- list(1:2, TRUE, 1:2)
slicem(a,idx)
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
, , 2
[,1] [,2] [,3]
[1,] 10 13 16
[2,] 11 14 17
library(abind)
nistfun <- function(a,list_o_idx,drop=FALSE){
lens <- lengths(list_o_idx)
do.call(abind, lapply(seq.int(max(lens)), function(i)
slicem(a, mapply(`[`, list_o_idx, pmin(lens,i), SIMPLIFY=FALSE), drop=drop)
))
}
# usage for OP's new example
nistfun(a, idx)
# , , 1
#
# [,1] [,2] [,3]
# [1,] 1 4 7
#
# , , 2
#
# [,1] [,2] [,3]
# [1,] 11 14 17
nistfun(a, idx, drop=TRUE)
# [1] 1 4 7 11 14 17
matrix( nistfun(a, idx), max(lengths(idx)), dim(a)[sapply(idx,isTRUE)]), byrow=TRUE)
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 11 14 17