rnorouzian
rnorouzian

Reputation: 7517

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!

Upvotes: 0

Views: 62

Answers (1)

Edgar Santos
Edgar Santos

Reputation: 3504

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

Upvotes: 1

Related Questions