英文:
Julia function for conditional proportions given margins of multi-dimensional array
问题
我是新手Julia,正在寻找一个函数来计算多维数组在给定维度上的比例。基本上,它是将数组的每个元素除以所需维度中元素的总和。在R中,proportions()
是一个执行此操作的函数。
英文:
I am new to Julia and looking for a function to compute the proportions of multidimensional array give some dimensions as margin. Basically, it is dividing each element of the array by the sum of element in the desired dimensions. In R, proportions()
is a function to do this.
答案1
得分: 2
经过一些搜索,感谢 @DNF,我提出了这个函数:
function proportions(x; d = 1)
dim = (setdiff(1:ndims(x), d)...,)
return x ./ sum(x, dims = dim)
end
以及类似的函数,用于等效的R函数marginSums()
:
function marginSums(x; d = 1)
dim = (setdiff(1:ndims(x), d)...,)
return dropdims(sum(x, dims = dim), dims = dim)
end
英文:
After some search and thanks to @DNF, I came up with this function:
function proportions(x; d = 1)
dim = (setdiff(1:ndims(x), d)...,)
return x ./ sum(x, dims = dim)
end
and a similar function for the equivalent R function marginSums()
:
function marginSums(x; d = 1)
dim = (setdiff(1:ndims(x), d)...,)
return dropdims(sum(x, dims = dim), dims = dim)
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论