Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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_Min - Fatal编程技术网

Arrays R-查找数组维度上的唯一最小值

Arrays R-查找数组维度上的唯一最小值,arrays,r,min,Arrays,R,Min,在4D数组中,我想找到第四维的唯一最小值。我想得到最小值的数组索引矩阵 我已尝试使用以下代码块解决该问题。我本想使用which.min,但我还没有找到返回数组索引的好方法 dims =c(3,3,3,4) # create sample data with multiple mins in [,,,1] mat_rep = array(c(rep(0,3),sample(1:prod(dims))), dim = dims) pos_rep = apply(mat_rep, 4, functi

在4D数组中,我想找到第四维的唯一最小值。我想得到最小值的数组索引矩阵

我已尝试使用以下代码块解决该问题。我本想使用
which.min
,但我还没有找到返回数组索引的好方法

dims =c(3,3,3,4)

# create sample data with multiple mins in [,,,1]
mat_rep = array(c(rep(0,3),sample(1:prod(dims))), dim = dims)
pos_rep = apply(mat_rep, 4, function(x) which(x == min(x), arr.ind = T)) # get position of unique minimum 

# create sample data with unique min
mat_norep = array(sample(1:prod(dims)), dim = dims)
pos_norep = apply(mat_norep, 4, function(x) which(x == min(x), arr.ind = T))

# formating depending on class of pos_ object
format_pos = function(x, dims){
  if(class(x) == "matrix") x = t(x)
  if(class(x) == "list") x = do.call(rbind, lapply(x, head, 1))
  x = cbind(x, 1:dims[4]) # add 4th dimension
  return(x)
}

format_pos(pos_norep, dims = dims)
format_pos(pos_rep, dims = dims)
所描述的解决方案是有效的,但是它通常不起作用,我认为
if(class())
cbind(x,1:dims[4])
容易产生错误。
有人有更干净的方法来解决这个问题吗?

要创建统一的输出,您可以显式地调用
arrayInd
apply(…,which.min)
的输出,而不是像
which(…,arr.ind=TRUE)
那样隐式调用。第四维索引仍然需要手动添加,尽管:

##使用1D值添加4D索引
start.ind[,1][,2][,3][,4]
#> [1,]    1    1    1    1
#> [2,]    1    3    3    2
#> [3,]    1    3    2    3
#> [4,]    3    1    1    4
arrayInd(应用(mat_norep,4,其中.min)+start.ind,.dim=dims)
#>      [,1] [,2] [,3] [,4]
#> [1,]    2    1    3    1
#> [2,]    1    2    1    2
#> [3,]    1    2    1    3
#> [4,]    2    2    3    4
##使用cbind添加4D索引
cbind(阵列ID(应用(材料代表,4,其中.min),.dim=头部(尺寸,3)),序号(尺寸[4]))
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    1    1    1
#> [2,]    1    3    3    2
#> [3,]    1    3    2    3
#> [4,]    3    1    1    4
cbind(排列(应用(mat_norep,4,其中.min),.dim=头部(dims,3)),序号(dims[4]))
#>      [,1] [,2] [,3] [,4]
#> [1,]    2    1    3    1
#> [2,]    1    2    1    2
#> [3,]    1    2    1    3
#> [4,]    2    2    3    4
数据

dims