Emma
Emma

Reputation: 31

How to set up a which function in R

I am a complete beginner with regards to using R. I was wondering if anyone could help me set up a which function. I have the following code:

    n_repeats <- 1000
    result <- rep(0, 1000)

    for (i in 1:n_repeats) { 
       sample_population<-rnorm(n = 20, mean = 0, sd = 1)
       result[i] <- t.test(sample_population)$p.value
    }

I wish to use the which function to determine the number of times I observe p values less than 0.1, 0.05 and 0.01

Upvotes: 2

Views: 153

Answers (2)

zx8754
zx8754

Reputation: 56219

Try this example:

#reproducibility
set.seed(123)
n_repeats <- 10

#permute
res <- sapply(1:n_repeats,function(i){
  sample_population <- rnorm(n=20,mean=0,sd=1)
  t.test(sample_population)$p.value
}) 

#sample_pvalues
res
#[1] 0.52274134 0.78537647 0.62458875 0.58798328 0.05731831 0.03346176 0.87611218 0.46173318 0.49516940 0.51989789

#which ones are less than 0.1
which(res<0.1)
#[1] 5 6

#Get counts per pvalue groups
table(cut(res,c(0,0.001,0.01,0.1)))
#(0,0.001] (0.001,0.01]   (0.01,0.1] 
#        0            0            2

Upvotes: 3

Tim
Tim

Reputation: 7464

Another, simple way of doing it is with replicate function dedicated for such usages

fun <- function() {
  sample_population <- rnorm(n = 20, mean = 0, sd = 1)
  t.test(sample_population)$p.value
}

out <- replicate(1000, fun())

sum(out < 0.1)   # for number of occurrences
mean(out < 0.1)  # for proportion of occurrences

Upvotes: 5

Related Questions