是否有可能`for`循环R中的'sapply`?

时间:2017-07-20 22:30:30

标签: r function for-loop optimization sapply

我想知道为什么我的对象CI无法正确返回以下函数中for()循环的完整(11个配对答案)输出?相反,CI会返回11个单个数字。

N = 30 ; df = 118 ; d = 1

f <- function (ncp, alpha, q, df) {
 abs(suppressWarnings(pt(q = d*sqrt(N), df = df, ncp, lower.tail = FALSE)) - 
   alpha)
      }

 a = mapply(c, as.list(20:30), as.list(-20:-30), SIMPLIFY = FALSE) # a list of paired values

 CI <- numeric(length(a))

 for(i in 1:length(a)){

CI[i] = sapply(c(0.025, 0.975),
         function(x) optimize(f, interval = a[[i]], alpha = x, q = d*sqrt(N), df = df, tol = 1e-10)[[1]])

    }  

CI # just returns one paired of the 11 paired answers expected!

1 个答案:

答案 0 :(得分:1)

怎么样:

N = 30 ; df = 118 ; d = 1

f <- function (ncp, alpha, q, df) {
  abs(suppressWarnings(pt(q = d*sqrt(N), df = df, ncp, lower.tail = FALSE)) - 
        alpha)
}

a = mapply(c, as.list(20:30), as.list(-20:-30), SIMPLIFY = FALSE) # a list of paired values

CI <- matrix(NA, 11,2)

for(i in 1:length(a)){

  CI[i,] = sapply(c(0.025, 0.975),
              function(x) optimize(f, interval = a[[i]], alpha = x, q = d*sqrt(N), df = df, tol = 1e-10)[[1]])

}  

CI