[R] Odp: Need help with function writing

Petr PIKAL petr.pikal at precheza.cz
Thu Sep 27 09:50:39 CEST 2007


Hi

> 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? 

Without going too deep into your function if you want to have a selection 
criteria which test to perform and some information in the result you can 
use a logical value in function definition

function(yvec, trtvec, alpha=0.05, header="", two=T) {

than put

if (two) {

result <- make two sided calculation} else {

result <- make one sided calculation)

and than 

out=data.frame(diff12estimate,stderr,tratio,twosidedP,lower,upper,alpha)
names(out)=c("Estimator","SE","T","P-value","Lower CI","Upper 
CI","Confidence")
out <- list(out, hypot=if(two) "two sided" else "one sided")
out
}

<end of function>

Regards
Petr
> 
> 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
> }
> 
> ______________________________________________
> R-help at r-project.org 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.



More information about the R-help mailing list