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 1 0 0 1
> B 1 0 -1 0 0
> C 1 0 -1 1 -1
> A 2 1 1 -1 0
> B 2 -1 0 0 1
> C 2 1 0 1 -1
>
> I would like to have two new dataframes so that
> Dataframe1: with the count of all 1
>
> Clinic ColM1 ColM2 ColM3 .. ColM40
> A 2 1 0 1
> B 0 0 0 1
> C 1 0 2 0
>
> Dataframe2: with the count of all -1
>
> Clinic ColM1 ColM2 ColM3 .. ColM40
> A 0 0 1 0
> B 1 1 0 0
> C 0 1 0 2
>
>
> Is there an easy way to achieve this.
> Thx,
> Bert