i want to calculate the p-value of a statistics test using R. I'm aware of the existing function t.test(x) but what i want to do is to determine the p value through monte carlo simulations. Therefore i defined this code:
mean.test <- function(x, y, B=10000,
alternative=c("two.sided","less","greater"))
{
p.value <- 0
alternative <- match.arg(alternative)
s<-replicate(B, (mean(sample(c(x,y), B, replace=TRUE))-mean(sample(c(x,y),
B, replace=TRUE)))) # random samples of test statistics
t <- mean(x) - mean(y) #teststatistics t
p.value <- 2 * (1- pnorm(mean(s))) #try to calculate p value
data.name <- deparse(substitute(c(x,y)))
names(t) <- "difference in means"
zero <- 0
names(zero) <- "difference in means"
return(structure(list(statistic = t, p.value = p.value,
method = "mean test", data.name = data.name,
observed = c(x,y), alternative = alternative,
null.value = zero),
class = "htest"))
}
When running
> set.seed(0)
> mean.test(rnorm(1000,3,2),rnorm(2000,4,3))
this is supposed to return
mean test
data: c(rnorm(1000, 3, 2), rnorm(2000, 4, 3))
difference in means = -1.0967, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
this return this though:
mean test
data: c(rnorm(1000, 3, 2), rnorm(2000, 4, 3))
difference in means = -1.0967, p-value = 0.9999
alternative hypothesis: true difference in means is not equal to 0
What's the error ?
t <- mean(x) - mean(y) #teststatistics t
andp.value <- 2 * (1- pnorm(mean(s))) #try to calculate p value
... confuse me. I don't get how this is supposed to give you a p-value, since the sample value (t) doesn't come into the calculation of the p-value. What are you trying to do there? $\endgroup$