-1

I have written a function, but I was wondering how I could have the function repeat by applying the seq(0, 1.5, by =.1) in place of a?

Here is my R code:

n1 = 20
n2 = 20
T1 = -1.26491106 
df = 38
a = "wide" 
nb <- (n1*n2)/(n1+n2)
a = c(medium = 1/2, wide = sqrt(2)/2, verywide = 1)[[a]]


OO <- function(t,nb,df,a){

integrand <- function(g){

  (1+nb*g)^(-1/2)*(1+t^2/(df*(1+nb*g)))^(-(df+1)/2)*(2*pi)^(-1/2)*g^(-3/2)*exp(-a^2/(2*g))
}

num <- a*integrate(integrand,0,Inf)$value

denom <- (1+t^2/df)^(-(df+1)/2)

return(num/denom)
}

OO(t=T1,nb=nb,df=df,a=a)  ## HERE IS THE FUNCTION ##
rnorouzian
  • 7,397
  • 5
  • 27
  • 72

1 Answers1

1

Not sure what is the meaning of initial setting on a, but here is how to apply function on a sequence,

sapply(seq(0.1, 1.5, by =.1), function(a) OO(t=T1,nb=nb,df=df,a=a))

gsun
  • 417
  • 3
  • 7
  • gsun, has now throgh `sapply` the `OO()` produced a vector each of whose elements are the answers of `OO()` if we individually had input `seq(0.1, 1.5, by =.1)` one number at a time? – rnorouzian Feb 02 '17 at 21:52
  • Yes. It's same with input one at a time in a loop. I believe apply function will be faster than loop, and one line code is cleaner, from my perspective. – gsun Feb 03 '17 at 03:55