shabbychef / madness

Multivariate Automatic Differentiation R package
GNU Lesser General Public License v3.0
31 stars 0 forks source link

colSums behavior with 3d arrays #17

Closed ZTaylor205 closed 6 years ago

ZTaylor205 commented 6 years ago

colSums appears to flatten its results, even when it is not supposed to.

test = array(rnorm(15),dim = c(5,5,3))
> colSums(test)
           [,1]       [,2]       [,3]
[1,]  0.4649005 -2.8809500 -4.6437586
[2,] -4.6437586  0.4649005 -2.8809500
[3,] -2.8809500 -4.6437586  0.4649005
[4,]  0.4649005 -2.8809500 -4.6437586
[5,] -4.6437586  0.4649005 -2.8809500
> val(colSums(madness(test)))
            [,1]
 [1,]  0.4649005
 [2,] -4.6437586
 [3,] -2.8809500
 [4,]  0.4649005
 [5,] -4.6437586
 [6,] -2.8809500
 [7,]  0.4649005
 [8,] -4.6437586
 [9,] -2.8809500
[10,]  0.4649005
[11,] -4.6437586
[12,] -2.8809500
[13,]  0.4649005
[14,] -4.6437586
[15,] -2.8809500

Unfortunately, there is no way to wrap this column back into a 5x3 vector. (I'll post this as its own issue.)

I tried to do a workaround with apply, but this results in a different error:

> apply(madness(test),2,sum)
Error in if (d2 == 0L) { : missing value where TRUE/FALSE needed
> apply(madness(test),1,sum)
Error in aperm.default(a@val, perm = perm, resize = resize) : 
  'perm' is of wrong length 3 (!= 1)
> apply(madness(test),3,sum)
Error in if (d2 == 0L) { : missing value where TRUE/FALSE needed
shabbychef commented 6 years ago

I see in the help for madness::colSums:

Note that the sums are flattened to a column vector.

I am not sure why I chose to do that. I seem to remember something repugnant about the differences of colSums and rowSums that modifying the output was the only sensible option, but I could be wrong. In the meantime, use assignment into dim to do the reshape:

set.seed(1234)
test = array(rnorm(15),dim = c(5,5,3))
mt <- madness(test)
cmt <- colSums(mt)
dim(cmt) <- c(5,3)
cmt@val

Also note it is probably not a good idea to rep out the data before stuffing into a madness object if the data are forced to be equal to each other.

ZTaylor205 commented 6 years ago

Thanks! I must have missed that warning, and I did not even realize you could use dim() to assign new dimensions.