The hypothesis test functions in the stats package use classic S3 object-orientated programming. You write a function that creates a "htest"
object, which is a list with a standard set of components, and R has a built-in print
method for objects of that class. The user-level function is traditionally called something like yourname.test
but can have any name. It can have any appropriate arguments.
- Type ?t.test to see the definition of a
"htest"
object. - See
stats:::t.test.default
to see an example of a function that creates a"htest"
object. - See
stats:::print.htest
to see how the user-friendly output is created.
Here is a toy example that performs a very simple chisquare test:
demo.test <- function(s2, df=1)
{
pval <- pchisq(s2, df, lower.tail=FALSE)
out <- list(
statistic=s2,
parameter=NULL,
p.value=pval,
null.value=NULL,
alternative="greater",
method="demo",
data.name=NULLname="s2")
class(out) <- "htest"
out
}
Then
> TEST <- demo.test(30, df=10)
> TEST
demo
data: s2
= 30, p-value = 0.0008566
alternative hypothesis: greater
If you want to be fancier, you can make your function S3 generic (like the stats package functions) in order to handle different types of input (e.g., a formula instead of data vectors). But an ordinary function like the above example might satisfy your needs.