0

我正在尝试从 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)
}
4

2 回答 2

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

于 2019-08-21T07:31:02.510 回答
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
          )
      )
于 2019-08-21T07:38:31.700 回答