Import your data:
test <- read.table(header=TRUE,textConnection("Group Result cens
A 1.3 1
A 2.4 0
A 2.1 0
B 1.2 1
B 1.7 0
B 1.9 0"))
Though there are many ways to do this, using by
specifically you could do something like this (assuming your dataframe is called test
):
by(test,test$Group,function(x) mean(x$Result[x$cens==1]))
which will give you the mean of all the Results
values within each group which have cens==1
Output looks like:
test$Group: A
[1] 1.3
----------------------------------------------------------------------
test$Group: B
[1] 1.2
To help you understand how this might work with your function, consider this:
If you just ask the by
statement to return
the contents of each group, you will get:
> by(test,test$Group,function(x) return(x))
test$Group: A
Group Result cens
1 A 1.3 1
2 A 2.4 0
3 A 2.1 0
-----------------------------------------------------------------------
test$Group: B
Group Result cens
4 B 1.2 1
5 B 1.7 0
6 B 1.9 0
...which is actually 2 data frames with only the rows for each group, stored as a list:
This means you can access parts of the data.frames for each group as you would before they they were split up. The x
in the above functions is referring to the whole sub-dataframe for each of the groups. I.e. - you can use individual variables as part of x
to pass to functions - a basic example:
> by(test,test$Group,function(x) x$Result)
test$Group: A
[1] 1.3 2.4 2.1
-------------------------------------------------------------------
test$Group: B
[1] 1.2 1.7 1.9
Now, to finally get around to answering your specific query!
If you take an example function which gets the mean of two inputs separately:
sumStats = function(var1, var2) {
res1 <- mean(var1)
res2 <- mean(var2)
output <- c(res1,res2)
return(output)
}
You could call this using by
to get the mean of both Result
and cens
like so:
> by(test,test$Group,function(x) sumStats(x$Result,x$cens))
test$Group: A
[1] 1.9333333 0.3333333
----------------------------------------------------------------------
test$Group: B
[1] 1.6000000 0.3333333
Hope that is helpful.