In: Statistics and Probability
What am I doing wrong in my bootstrap code for R?
x<-c(30, 37, 36, 43, 42, 43, 43, 46, 41, 42)
n = 10
x=pnorm(n,mean=40.3,sd=4.6)
mu_0=40.3
s.mean=mean(x)
s.sd=sd(x);s.sd
[1] NA
t.sample=(s.mean-mu_0)/(s.sd/sqrt(n))
B=10000
t=c()
count.less=0
count.more=0
for(j in 1:B)
+ { b.smpl = x[sample(1:n, size = n,replace=TRUE)]
+ ybar.bs = mean(b.smpl)
+ sd.bs = sd(b.smpl)
+ t[j] = (ybar.bs - s.mean)/(sd.bs/sqrt(n))
+ if(t[j]>=t.sample){ count.more=count.more+1}
+ if(t[j]<=t.sample){ count.less=count.less+1}
+ }
Error in if (t[j] >= t.sample) { : missing value
where TRUE/FALSE needed
pvalue.right=count.more/B;pvalue.right
[1] 0
pvalue.left=count.less/B;pvalue.left
[1] 0
pvalue/two=2*min(pvalue.right,pvalue.left)
Error in pvalue/two = 2 * min(pvalue.right,
pvalue.left) :
object 'pvalue' not found
why error has occur in your code is written in Comment using #
x<-c(30, 37, 36, 43, 42, 43, 43, 46, 41, 42)
n = 10
x=pnorm(n,mean=40.3,sd=4.6) # here your using x again which
already used in first line of code so change it
mu_0=40.3
s.mean=mean(x)
s.sd=sd(x);s.sd # here we getting NA because in the 3rd
line of code your using x=pnorm(n,mean=40.3,sd=4.6) and
its output will be single number so NA occurs
[1] NA
t.sample=(s.mean-mu_0)/(s.sd/sqrt(n))
B=10000
t=c()
count.less=0
count.more=0
for(j in 1:B)
+ { b.smpl = x[sample(1:n, size = n,replace=TRUE)]
+ ybar.bs = mean(b.smpl)
+ sd.bs = sd(b.smpl)
+ t[j] = (ybar.bs - s.mean)/(sd.bs/sqrt(n))
+ if(t[j]>=t.sample){ count.more=count.more+1}
+ if(t[j]<=t.sample){ count.less=count.less+1}
+ }
Error in if (t[j] >= t.sample) { : missing value
where TRUE/FALSE needed # when you do the changes which are mention
above this error will not occur
pvalue.right=count.more/B;pvalue.right
[1] 0
pvalue.left=count.less/B;pvalue.left
[1] 0
pvalue/two=2*min(pvalue.right,pvalue.left) # here you
should
use pvalue=2*min(c(pvalue.right,pvalue.left))
Error in pvalue/two = 2 * min(pvalue.right,
pvalue.left) :
object 'pvalue' not found
Corrected R-code
x<-c(30, 37, 36, 43, 42, 43, 43, 46, 41, 42)
n = 10
p=pnorm(n,mean=40.3,sd=4.6)
mu_0=40.3
s.mean=mean(x)
s.sd=sd(x);s.sd
t.sample=(s.mean-mu_0)/(s.sd/sqrt(n))
B=10000
t=c()
count.less=0
count.more=0
for(j in 1:B)
{ b.smpl = x[sample(1:n, size = n,replace=TRUE)]
ybar.bs = mean(b.smpl)
sd.bs = sd(b.smpl)
t[j] = (ybar.bs - s.mean)/(sd.bs/sqrt(n))
if(t[j]>=t.sample){ count.more=count.more+1}
if(t[j]<=t.sample){ count.less=count.less+1}
}
pvalue.right=count.more/B
pvalue.right
pvalue.left=count.less/B
pvalue.left
pvalue=2*min(c(pvalue.right,pvalue.left))
pvalue