[R] Need help with function writing

Letticia Ramlal lramlal at claflin.edu
Tue Sep 25 15:20:07 CEST 2007


Hello: 

If anyone could guide me with this I would greatly appreciate it. Thanking you in advance for your assistance.

Using a 3-level input factor alternative so that a function(below) can compute both a two-sided and one-sided p-values. Making the two-sided test the default. And produce output information about which alternative was tested. Where would I place the ifelse statement? 

function(yvec,trtvec,alpha=0.05,header="") {
#################################################
# A function to compute a two-sample t-test and confidence 
# interval (equal-variance, independent samples).  yvec is 
# a numeric vector containing both samples' data.  trtvec 
# is a vector, same length as yvec, of treatment
# identifiers for the data in yvec.  A boxplot comparing
# the treatments' data is constructed.  Output is a one-row
# data frame reporting the results of the test and 
# confidence interval
##################################################
trtvec=as.factor(trtvec)
boxplot(split(yvec,trtvec))
title(header)
ybar=tapply(yvec,trtvec,mean)
varvec=tapply(yvec,trtvec,var)
nvec=table(trtvec)
error.df=nvec[1]+nvec[2]-2
pooled.var=((nvec[1]-1)*varvec[1]+(nvec[2]-1)*varvec[2])/error.df
diff12estimate=ybar[1]-ybar[2]
stderr=sqrt(pooled.var*((1/nvec[1])+(1/nvec[2])))
tratio=diff12estimate/stderr
twosidedP=2*(1-pt(abs(tratio),error.df))
tcrit=qt(1-alpha/2,error.df)
lower=diff12estimate-tcrit*stderr
upper=diff12estimate+tcrit*stderr
calpha=1-alpha
out=data.frame(diff12estimate,stderr,tratio,twosidedP,lower,upper,alpha)
names(out)=c("Estimator","SE","T","P-value","Lower CI","Upper CI","Confidence")
out
}



More information about the R-help mailing list