简体   繁体   中英

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)
}

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 .

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
          )
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM