Search code examples
rlistfunctionvectorizationintegral

subsetting from a fully vectorized function in R?


I have written the Vectorized "main" function below which lists three objects: BF10, p.value and d.

I'm wondering WHY when saving the "main" function call as an object like b (see below), then I can NOT subset BF10, p.value or d from b?

That is, after running the main function, when I when I run:

b = BF.d.pvalue(t = c(2.46, 3.21), n1 = c(20, 30), n2 = c(20, NA))
b$BF10   ;  b$p.value   ;   b$d  ## None of these return anything !!!

Here is the "main" function:

BF.d.pvalue = Vectorize(function(t, n1, n2 = NA, scale = sqrt(2)/2){

      options(warn = -1)  
      N = ifelse(is.na(n2), n1, (n1*n2)/(n1+n2))
     df = ifelse(is.na(n2), n1 - 1, (n1 + n2) - 2)
      d = t / sqrt(N)

     H1 = integrate(function(delta)dcauchy(delta, 0, scale)*dt(t, df, delta*sqrt(N)), -Inf, Inf)[[1]]
     H0 = dt(t, df)
   BF10 = H1/H0
p.value = 2*(1-pt(abs(t), df))

cbind(BF10 = BF10, p.value = p.value, d = d)

}, vectorize.args = c("t", "n1", "n2", "scale"))

Solution

  • mapply does simplification by default. Here result has been simplified to a matrix. You can do

    b["BF10", ]
    b["p.value", ]
    b["d", ]
    

    Although you can set SIMPLIFY = FALSE, but the result is a nested list.

    If you want something like a list / data frame where you can use $, how about

    b <- data.frame(t(b))