[R] Using power.t.test over a range of conditions

Chuck Cleland ccleland at optonline.net
Fri Apr 20 19:54:48 CEST 2007


Inman, Brant A. M.D. wrote:
> R-Helpers:
> 
> I would like to perform sample size calculations for an experiment.  As
> part of this process, I would like to know how various assumptions
> affect the sample size calculation.  For instance, one thing that I
> would like to know is how the calculated sample size changes as I vary
> the difference that I would like to detect.  I tried the following
> first, but got the associated error message.
> 
> -----------------
> 
>> power.t.test(delta=seq(500,2000,100), sd=1000, sig.level=0.05,
> power=0.8,
> + type='two.sample', alt='two.sided')
> 
> Error in uniroot(function(n) eval(p.body) - power, c(2, 1e+07)) : 
>         invalid function value in 'zeroin'
> In addition: Warning message:
> the condition has length > 1 and only the first element will be used in:
> if (f(lower, ...) 
> * f(upper, ...) >= 0) stop("f() values at end points not of opposite
> sign") 
> 
> -----------------
> 
>>From the error message I suspected that the function did not handle
> vectors as arguments.  I therefore tried the following looping structure
> to solve the problem:
> 
> -----------------
> 
> 
> DELTA  <- seq(500,2000,250)
> SD	 <- seq(1000,2500,250)
> result <- matrix(nrow=length(DELTA), ncol=length(SD))
> 	colnames(result) <- paste('SD=',SD, sep='')
> 	rownames(result) <- paste('Delta=',DELTA, sep='')
> 
> for(i in 1:length(DELTA)){
> 	for(j in 1:length(SD)){
> 		result[i,j] <- power.t.test(delta=DELTA[i], sd=SD[j],
> sig.level=0.05, power=0.8,
> 			type='two.sample', alt='two.sided')
> 	}
> }
> 
> Error in result[i, j] <- power.t.test(delta = DELTA[i], sd = SD[j],
> sig.level = 0.05,  : 
>         number of items to replace is not a multiple of replacement
> length
> 
> -----------------
> 
> Can some one tell me what I am doing wrong here?

  I think one problem you are having is that power.t.test() returns a
list with multiple components.
  Perhaps you could go about it like this:

df <- data.frame(expand.grid(DELTA = seq(500,2000,250),
                             SD = seq(1000,2500,250)))

df$N <- NA

for(i in 1:dim(df)[1]){
df$N[i] <- power.t.test(delta=df$DELTA[i], sd=df$SD[i],
                        sig.level=0.05, power=0.8,
                        type='two.sample', alt='two.sided')$n
}

> Thanks in advance for your help,
> 
> Brant Inman
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list