我正在尝试规范化指定维度内的数组 (通过标准化,我的意思是将每个元素除以相关维度上的总和)。
我想以某种方式自动化计算,其中给出了规范化数组的维度, 并且每个都使用相同的函数来生成输出。虽然我可以生成所需的金额,但我不能 用一致的技术对它们进行标准化。
Mwe
a = array(1:8, c(2,2,2))
dm = 1 # dimension to sum over
ndim = length(dim(a))
margin = setdiff(seq_len(ndim), dm) # dimensions to keep in apply
a / rep(apply(a, margin, sum), each=2)
, , 1
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
, , 2
[,1] [,2]
[1,] 0.4545455 0.4666667
[2,] 0.5454545 0.5333333
dm = 3 # dimension to sum over
ndim = length(dim(a))
margin = setdiff(seq_len(ndim), dm)
a / rep(apply(a, margin, sum), times=2)
# but for this dimension `times`, instead of `each` was used
, , 1
[,1] [,2]
[1,] 0.1666667 0.3000000
[2,] 0.2500000 0.3333333
, , 2
[,1] [,2]
[1,] 0.8333333 0.7000000
[2,] 0.7500000 0.6666667
#for dim=2 the denominator is more difficult to generate
dm = 2 # dimension to sum over
a / c(4,6,4,6,12,14,12,14)
虽然最好不要使用循环(包括应用等),但欢迎使用任何解决方案。感谢
根据评论中的要求,关于矩阵的一个例子(如果它只是2x2阵列,这将更直接)
a = array(1:4, c(2,2))
a
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
dm = 1 # dimension to sum over
ndim = length(dim(a))
margin = setdiff(seq_len(ndim), dm) # dimensions to keep in apply
apply(a, margin, sum)
# [1] 3 7
a / rep(apply(a, margin, sum), each=2)
# [,1] [,2]
#[1,] 0.3333333 0.4285714
#[2,] 0.6666667 0.5714286
dm = 2 # dimension to sum over
ndim = length(dim(a))
margin = setdiff(seq_len(ndim), dm) # dimensions to keep in apply
apply(a, margin, sum)
# [1] 4 6
a / rep(apply(a, margin, sum), times=2)
# [,1] [,2]
#[1,] 0.2500000 0.7500000
#[2,] 0.3333333 0.6666667
答案 0 :(得分:3)
您可以使用sweep:
获取所寻求的一致性normalize <- function(a,dm){
ndim <- length(dim(a))
margin <- setdiff(seq_len(ndim),dm)
sweep(a,margin,apply(a, margin, sum),"/")
}
然后normalize(a,1)
,normalize(a,2)
和normalize(a,3)
简化了您想要的数组。