Andy Radisavljevic
Andy Radisavljevic

Reputation: 11

How to create a vector when using For Loop?

I am trying to conduct a two sided sign test from 10,000 random normal samples of size 30. I am trying to extract the p-values given from the binom.test and put them into a vector but can't quite figure out how to execute this.

set.seed(100)
sample <- matrix(rnorm(300000, mean=0.1, sd=1), 10000, 30)

success <- ifelse(sample>=0, 1, 0)
success

#sample[1,]
#success[1,]
#sum(success[1,])
#for loop
for(i in 1:10000){
        pvalue<- binom.test(sum(success[i,]), 30, p=0.5, 
                             alternative = c("two.sided"), 
                             conf.level = 0.95)$p.value
        p_values_success <- ifelse(pvalue<=0.05, 1, 0)
}

Upvotes: 0

Views: 60

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389265

I guess what you are trying to do is

pvalue <- numeric(length = 1000L)
p_values_success <- numeric(length = 1000L)

for(i in 1:10000) {
  pvalue[i] <- binom.test(sum(success[i,]), 30, p=0.5, 
                  alternative = c("two.sided"), 
                  conf.level = 0.95)$p.value
  p_values_success[i] <- ifelse(pvalue[i]<=0.05, 1, 0)
}

However, if I had to rewrite you code completely from scratch I would do

set.seed(100)
sample <- matrix(rnorm(300000, mean=0.1, sd=1), 10000, 30)
success[] <- as.integer(sample >=0)

t(apply(success, 1, function(x)  {
    p_val <- binom.test(sum(x), 30, p=0.5,alternative = c("two.sided"),
             conf.level = 0.95)$p.value
    c(p_val, as.integer(p_val<=0.05))
}))

This will return a 2-column matrix where 1st column is pvalue and the second one is p_values_success.

Upvotes: 1

MKa
MKa

Reputation: 2318

You could also do:

apply(success, 1, 
      FUN = function(x) 
        ifelse(
          binom.test(sum(x), 30, p = 0.5, 
                     alternative = "two.sided", conf.level = 0.95)$p.value <= 0.05, 1, 0
          )
      )

Upvotes: 0

Related Questions