PDA

View Full Version : R code and arrays


stats student
04-12-08, 05:30 AM
Doing a stats project using R and just can't get it to work - I want to put my results from the function size() into an array.
At the moment I keep getting the error message:
Error in res[distribution, test, samplesize] <- results :
subscript out of bounds
Can anyone tell me where I'm going wrong, please?!


size.power.test<-function(){
k<-1000
distributions<-c("Normal","Uniform")
tests<-c("t","Wilcoxon")
samplesizes<-c(10,30,40)
res<-array(0,c(length(distributions),length(tests),leng th(samplesizes)))
dimnames(res)<-list(distributions,tests,samplesizes)
for(distribution in distributions){
for(test in tests){
for(samplesize in samplesizes){
for(i in 1:k){
results<-size()
res[distribution,test,samplesize]<-results
}
output<-size.power.test
return(output)
}
}
}
}

size<-function(k=1000,H0=0,mu.true=0,mu.false=0.5,sigma. true=1,alpha=0.05,
x1=-sqrt(3),y1=sqrt(3),x2=(0.5-sqrt(3)),y2=(0.5+sqrt(3))){
distributions<-c("Normal","Uniform")
tests<-c("t","Wilcoxon")
samplesizes<-c(10,30,40)
reject1<-numeric(k)
for(distribution in distributions){
for(test in tests){
for(samplesize in samplesizes){
for(i in 1:k){
if(distribution=="Normal"){
#randomly generate data from normal distribution with true mean
dat<-rnorm(n=samplesize,mean=mu.true,sd=sigma.true)
}else{
#randomly generate data from a uniform distribution
dat<-runif(samplesize,min=x1,max=y1)
}
if(test=="t"){
#perform a t-test on sample
res<-t.test(dat,alternative="two.sided",mu=H0)
#record if p-value is less than alpha
reject1[i]<-(res$p.value<=alpha)
}else{
#perform a wilcoxon-test on sample
res<-wilcox.test(dat,alternative="two.sided",mu=H0)
#record if p-value is less than alpha
reject1[i]<-(res$p.value<=alpha)
}
}
output<-list(sum(reject1)/k)
return(output)
}
}
}
}

Nico
04-12-08, 05:36 AM
Thread moved to Other Languages section.

stats student
04-12-08, 05:55 AM
Sorry - I'm new to the site!