使用For Loop时如何创建向量?

时间:2019-08-21 06:06:17

标签: r for-loop statistical-test

我正在尝试从10,000个大小为30的随机正常样本中进行双向符号测试。我正在尝试从binom.test中提取p值并将其放入向量中,但无法完全弄清楚该如何执行。

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

2 个答案:

答案 0 :(得分:1)

我想你想做的是

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

但是,如果我不得不从头开始完全重写代码,我会这么做

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

这将返回一个2列矩阵,其中第一列为pvalue,第二列为p_values_success

答案 1 :(得分:0)

您也可以这样做:

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