[R] Sum a list of tables

David Winsemius dwinsemius at comcast.net
Mon Aug 23 22:49:34 CEST 2010


On Aug 23, 2010, at 12:39 PM, Thaler, Thorn, LAUSANNE, Applied  
Mathematics wrote:

> Perfectly, works as expected. Regarding the other questions, can  
> anybody point me to the right direction?
>
>

>
> So first question: where is the `+` operation defined for tables?

tables are a modification via attributes of matrices.

> Is it
> S4? How can I see the source code of S4 functions

I don't think so, at least from reading:

?Arithmetic
?groupGeneric
?InternalMethods

> (I'm not very
> comfortable with S4)? Or in general how do I find all generic  
> functions
> for a specific class? I can get all S3 implementations of plot with
> methods(plot), I can get all S4 functions with getMethods(plot). But
> I've no idea of how to find all methods defined for a class? (e.g. all
> functions that operate on tables, say)
>
> Second question: my first dirty hack would be something like
>
> args <- list(...)
> table.sum <- args[[1]]
> for (i in 2:length(args)) table.sum <- table.sum + args[[i]]
>
>
> making use of the fact that `+` is defined for tables (and forgetting
> about cases where two tables don't feature the same names). It works,
> but isn't there a more elegant way to get the same?

Would sum() work better than "+"? The sum function is not a dyadic  
operator.

(a <- table(rep(1:3, sample(10,3))))
  k <- list(a,a,a)

 > Reduce(sum, k )
[1] 51
 > do.call("sum", k)
[1] 51
 >

>
> Last question: is there a way to determine the call stack, such that I
> can see the names of the function which are actually executed when I
> commit a command?

I know there is some feeling hereabouts that saying anything vaguely  
like RTFM (of RTFA's) is passe, but I do believe that you can find  
either the answer or pointers in the directions of an answer to this  
by reviewing the posting over this last weekend to a question about  
recovering from errors. (I was not the responder, so do not remember  
the subject line. Oh heck. .... search, search, search, ... there it  
is ... "on abort error, always show call stack?")

> I know a little about R's dispatching mechanism for S3
> classes (plot(a) actually calls plot.table) but I've no clue which
> function is called if I type a + a (especially since `+` belongs to  
> the
> generic function group Ops and I do not know at all whether its S4 or
> S3). I read the documentation about S3 Group Generic Functions and  
> tried
> to delve into S4,

Oh well. You've already been there. Maybe my advice above will help  
someone else.


> but obviously I was not able to understand everything
> completely. So it would be great if somebody could help me out with  
> this
> specific topic and point me to some resources where I can learn more.
>
> Thanks for your help in advance.
>
> BR,
>
> Thorn

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list