Prof Brian Ripley wrote:
On Thu, 21 Apr 2005, Ernesto Jardim wrote:

I'm using colSums and rowSums to sum the first dimensions of arrays. It works ok but the resulting object is different. See

a3d <- array(rnorm(120, mean=2), dim=c(20,6,1))
dim(colSums(a3d))

[1] 6 1

dim(rowSums(a3d))

NULL

class(colSums(a3d))

[1] "matrix"

class(rowSums(a3d))

[1] "numeric"

I was expecting rowSums to preserve the array class and the relevant dimensions (1,20).

The main problem is with arrays where the third dimension (or higher) is > 1. colSums preserve the array but rowSums concatenate the results:


No, it acts as documented.

a3d <- array(rnorm(120, mean=2), dim=c(20,3,2))
rowSums(a3d)

[1] 8.894178 11.932361 15.231601 12.374629 11.823671 10.564709 9.065166 [8] 13.900264 13.331756 9.351242 11.989821 7.643745 9.923288 8.169997 [15] 12.124624 16.711742 11.414150 15.221880 12.053734 13.368988

colSums(a3d)

[,1] [,2] [1,] 44.80941 29.49216 [2,] 42.18339 39.81121 [3,] 39.90528 38.89010

Is this on purpose ?


Yes, and documented.  rowSums(a3d) is a vector of length 20, by

    dims: Which dimensions are regarded as "rows" or "columns" to sum
          over.  For 'row*', the sum or mean is over dimensions
          'dims+1, ...'; for 'col*' it is over dimensions '1:dims'.

whereas colSums(a3d) is an array of dims c(6, 1).

Don't be confused by the class: there is no S3 class here.



Ok,

Thanks for the enlightment.

EJ

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to