简体   繁体   中英

Is it possible to `for` loop the `sapply` in R?

I was wondering why my object CI doesn't correctly return the full (11 paired answers) outputs from the for() loop in the following function? Instead, the CI returns 11 single numbers.

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!

How about:

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

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