[R] colSums and rowSums with arrays - different classes and dim ?

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Apr 21 15:51:42 CEST 2005


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.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list