Home > other >  element-wise calculation with arrays (tensors)
element-wise calculation with arrays (tensors)

Time:11-22

I have a 3-dimensional array x and want to calculate the share a of each element w.r.t. the 3rd dimension: share formula

I tried the following in R but this does not work due to "non-conformable arrays" (which makes sense of course).

x <- array(
  data = 1:8,
  dim = c(2, 2, 2),
  dimnames = list(i = c("i1", "i2"), j = c("j1", "j2"), k = c("k1", "k2")))

a <- x / apply(x, c(1, 2), sum)

So I am looking for a way to perform tensor calculations where I can specify the dimensions on which to perform the division. This is x and the sum as I already have it and a as I want it (a shown with fractions here):

> x
, , k = k1

    j
i    j1 j2
  i1  1  3
  i2  2  4

, , k = k2

    j
i    j1 j2
  i1  5  7
  i2  6  8


> apply(x, c(1, 2), sum)
    j
i    j1 j2
  i1  6 10
  i2  8 12


> a
, , k = k1
    j
i     j1   j2
  i1 1/6 3/10
  i2 2/8 4/12

, , k = k2
    j
i     j1   j2
  i1 5/6 7/10
  i2 6/8 8/12

I'm grateful for any hints!

CodePudding user response:

Try proportions

> proportions(x,1:2)
, , k = k1

    j
i           j1        j2
  i1 0.1666667 0.3000000
  i2 0.2500000 0.3333333

, , k = k2

    j
i           j1        j2
  i1 0.8333333 0.7000000
  i2 0.7500000 0.6666667
  • Related