[R] Conditional Sum

2007-02-06 Thread Bert Jacobs

Hi,

I would like to make a conditional sum for certain columns in a dataframe.

This is how my dataframe looks like:

Clinic Rep ColM1 ColM2 ColM3 ... ColM40
A  1 10  01
B  1 0-1 00
C  1 0-1 1-1 
A  2 11  -1   0
B  2 -1   0  01 
C  2 10  1   -1

I would like to have two new dataframes so that
Dataframe1: with the count of all 1

Clinic  ColM1  ColM2 ColM3 .. ColM40
A2  10 1
B0  00 1
C1  02 0

Dataframe2: with the count of all -1

Clinic  ColM1  ColM2 ColM3 .. ColM40
A0  01 0
B1  10 0
C0  10 2


Is there an easy way to achieve this.
Thx,
Bert

__
R-help@stat.math.ethz.ch 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.


Re: [R] Conditional Sum

2007-02-06 Thread Kaskelma, Heikki
Yes, consider:

df=data.frame(Clinic=rep(c(A, B, C), 2),
  Rep=c(1, 1, 1, 2, 2, 2),
  colM1=c(1, 0, 0, 1, -1, 1),
  ColM2=c(0, -1, -1, 1, 0, 0),
  ColM3=c(0, 0, 1, -1, 0, 1),
  ColM40=c(1, 0, -1, 0, 1, -1)
 )
Clinic=1; Rep=2
ff=function(x, v) sum(x == v)
Dataframe1=aggregate(df[, -c(Clinic, Rep)], df[Clinic], ff, 1)
names(Dataframe1)[1]=Clinic
Dataframe2=aggregate(df[, -c(Clinic, Rep)], df[Clinic], ff, -1)
names(Dataframe2)[1]=Clinic
Dataframe1
Dataframe2


Heikki Kaskelma

-- 
Bert Jacobs kirjoitti jokin aikaa sitten:
 I would like to make a conditional sum for certain columns in 
 a dataframe.
 
 This is how my dataframe looks like:
 
 Clinic Rep ColM1 ColM2 ColM3 ... ColM40
 A  1 10  01
 B  1 0-1 00
 C  1 0-1 1-1 
 A  2 11  -1   0
 B  2 -1   0  01 
 C  2 10  1   -1
 
 I would like to have two new dataframes so that
 Dataframe1: with the count of all 1
 
 Clinic  ColM1  ColM2 ColM3 .. ColM40
 A2  10 1
 B0  00 1
 C1  02 0
 
 Dataframe2: with the count of all -1
 
 Clinic  ColM1  ColM2 ColM3 .. ColM40
 A0  01 0
 B1  10 0
 C0  10 2
 
 
 Is there an easy way to achieve this.
 Thx,
 Bert

__
R-help@stat.math.ethz.ch 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.