Reputation:
I used a Monte carlo algorithm to generate data samples of size 100 of a geometric distribution using inversion sampling:
gi.cdf.geom <- function(p,u){
k <- c()
k <- ceiling(log(1-u)/log(1-p)) - 1
return(k)
}
The function above is the inverse of the CDF of a geometric distribution
u1 <- runif(100)
gen.gi.cdf1 <- gi.cdf.geom(50/239,u1)
as.data.frame(table(gen.gi.cdf1))
What I do not know how to do is randomly simulate a 1000 data samples of size 100 and to calculate the chi-square test statistic for each sample. My attempt at creating the samples is the following:
for(i in 1:1000){
n=100
p=50/239
{
u=runif(n)
values <- gi.cdf.geom(p,u)
}
print(values)
}
However this gives me all the samples of my console with no way of referring to them later.
I would really appreciate some help.
Thank you
Upvotes: 1
Views: 584
Reputation: 66834
Use replicate
. For example:
(x <- replicate(3,rgeom(10,50/239)))
[,1] [,2] [,3]
[1,] 5 3 12
[2,] 15 2 3
[3,] 5 5 0
[4,] 4 2 1
[5,] 13 0 8
[6,] 0 3 0
[7,] 3 1 6
[8,] 0 6 2
[9,] 0 4 4
[10,] 8 4 1
You can test on them using apply
apply(x,2,chisq.test)
[[1]]
Chi-squared test for given probabilities
data: newX[, i]
X-squared = 47.566, df = 9, p-value = 3.078e-07
[[2]]
Chi-squared test for given probabilities
data: newX[, i]
X-squared = 10, df = 9, p-value = 0.3505
[[3]]
Chi-squared test for given probabilities
data: newX[, i]
X-squared = 37.3243, df = 9, p-value = 2.303e-05
Warning messages:
1: In FUN(newX[, i], ...) : Chi-squared approximation may be incorrect
2: In FUN(newX[, i], ...) : Chi-squared approximation may be incorrect
Upvotes: 2