[S] conditioning computations on a data.frame

Renaud LANCELOT (lancelot@telecomplus.sn)
Fri, 29 May 1998 09:24:35 +0100


I use S+ 4.0 for Win95. I want to compute different statistics on 1 (or
more) column(s) of a data.frame conditionally on other columns and store the
results in an output data.frame together with the conditioning variables and
their values.

For example:

data <- data.frame(a = c(1, 1, 2, 2), b = c(1, 1, 2, 3), c = c(1, 2, 3, 4))
> data
a b c
1 1 1 1
2 1 1 2
3 2 2 3
4 2 3 4
> attach(data)
> data.list <- by.data.frame(data, list(a, b), function(x) {c(length(x[,
3]), sum(x[, 3]))})
> detach("data")

I would like the result to be:
a b l s
1 1 2 3
2 2 1 3
2 3 1 4

instead of

> data.list
a:1
b:1
[1] 2 3
------------------------------------------------------------------------------
a:2
b:1
NULL
------------------------------------------------------------------------------
a:1
b:2
NULL
------------------------------------------------------------------------------
a:2
b:2
[1] 1 3
------------------------------------------------------------------------------
a:1
b:3
NULL
------------------------------------------------------------------------------
a:2
b:3
[1] 1 4

I could use matrix(unlist()) but then I loose the names. What would you
suggest ?

Many thanks in advance.

Renaud
Renaud Lancelot
Programme PPR
ISRA-URA II
BP 2057
Dakar-Hann (Senegal)

Tel (221) 832 49 02
Fax (221) 821 18 79 / (221) 832 33 34

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news