I have an array and want to make a probability table for each matrix of dimensions 1 and 2. For example, consider this:
A <- array(1:12,c(2,2,3))
print(A)
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
, , 3
[,1] [,2]
[1,] 9 11
[2,] 10 12
I want each of the 2x2 matrices become probability tables with sum 1 for each, i.e. each 2x2 matrix is divided by its sum of element. For this, I ran the below code by first taking sum and then creating an array with the same dimension.
Asum <- apply(A,3,sum)
B <- array(rep(Asum,each=length(A[,,1])),dim(A))
A/B
, , 1
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
, , 2
[,1] [,2]
[1,] 0.1923077 0.2692308
[2,] 0.2307692 0.3076923
, , 3
[,1] [,2]
[1,] 0.2142857 0.2619048
[2,] 0.2380952 0.2857143
Is there a better way to do this?
CodePudding user response:
You can use proportions()
:
proportions(A, margin = 3)
, , 1
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
, , 2
[,1] [,2]
[1,] 0.1923077 0.2692308
[2,] 0.2307692 0.3076923
, , 3
[,1] [,2]
[1,] 0.2142857 0.2619048
[2,] 0.2380952 0.2857143