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

 

BR Thorn

 

From: RICHARD M. HEIBERGER [mailto:rmh@temple.edu] 
Sent: lundi 23 août 2010 18:36
To: Thaler,Thorn,LAUSANNE,Applied Mathematics
Cc: r-help@r-project.org
Subject: Re: [R] Sum a list of tables

 

Reduce(`+`, k)



On Mon, Aug 23, 2010 at 12:18 PM, Thaler, Thorn, LAUSANNE, Applied Mathematics <Thorn.Thaler@rdls.nestle.com> wrote:

Hi all,

In R it is possible to sum tables:

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

1 2 3
2 5 7

> a+a

 1  2  3
 4 10 14

Now suppose that I have a list of tables, where each table counts the
same things

> k <- list(a,a,a)

How can I sum all tables in k?

> do.call(sum, k)
[1] 42

does not work since it sums over each table.

> do.call(`+`, list(a,a))

 1  2  3
 4 10 14

works not with lists containing not exactly two values (since `+` takes
exactly 2 values). So I think I should write something like

Summary.table <- function(..., na.rm) {
 if (.Generic == "sum") {
    ...
 } else { # use the default method
    NextMethod()
 }
}

So first question: where is the `+` operation defined for tables? Is it
S4? How can I see the source code of S4 functions (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?

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 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, 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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




	[[alternative HTML version deleted]]

