Skip to content

function sum for array

1 message · William Dunlap

#
S+'s help(apply) says

  MARGIN 
  the subscripts over which the function is to be applied.
  For example, if X is a matrix, MARGIN=1 indicates rows
  and MARGIN=2 indicates columns. If the dimensions of X
  are named, then the names can be used to specify MARGIN.
  Note that MARGIN tells which dimensions of X are retained
  in the result.

(and the Details section of the help file gives a worked
example) but I don't know if that is any clearer to you
than R's help(apply).

So if you want to summarize the one-dimensional slices,
X[i,j,k],  of an I by J by K array X use MARGIN=c(1,2).
(If your summary has dimensions M by N by ... by P (or
just length M) then apply's output has dimensions
c(prod(M,N,...,P),K), except that any dimension equal to 1 is
dropped.) 

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 
From: Simone Salvadei [mailto:simone.salvadei at gmail.com] 
Sent: Thursday, November 17, 2011 11:20 PM
To: William Dunlap
Subject: Re: [R] function sum for array

thank you very much, despite of the fact that I didn't understand how it really works. Why have you put 1:2?
S
On Thu, Nov 17, 2011 at 9:40 PM, William Dunlap <wdunlap at tibco.com> wrote:
The following gives a result identical to your 'B'.
?> apply(A,1:2,sum)
? ? ? ? ?[,1] ? ?[,2] ? ? [,3]
?[1,] ?532610 2130440 ?8521760
?[2,] 1065220 4260880 17043520

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com