Reputation: 7517
I'm trying to loop over f
in my R code below. But f
itself is a function (i.e., is.function(f)
gives TRUE
).
I'm wondering given that f
is a function, is it possible to loop over it?
Note: f
comes from f <- approxfun(...)
and needs to remain as a function so I can use integrate(f, ...)
.
Here is my R code:
den = list()
x = rep(0, 2)
d = list(c(rbeta(1e4, 5, 5), rbeta(1e4, 2, 5)))
f = as.function() ## What should this be? ##
for(i in 1:2){
den[[i]] <- density(d[[i]])
f[i] <- approxfun(den[[i]]$x, den[[i]]$y, yleft = 0, yright = 0) # how can it become loopable?
x[i] <- integrate(f[i], 0, .1)[[1]]
}
Upvotes: 2
Views: 86
Reputation: 76663
Though there already is an accepted answer, I will post mine, since I believe that the main error in your code comes from trying too hard, you are complicating too much.
First of all, you don't need a list of functions f
, you only need one function to use with integrate
, like you say in the question.
Second, the way you created d
uses an unnecessary call to c
. This call will make of its arguments one vector, not two vectors of random beta numbers, which is what you want.
So the full code is just a simplification of yours.
set.seed(4149) # makes the results reproducible
den = list()
x = rep(0, 2)
d = list(rbeta(1e4, 5, 5), rbeta(1e4, 2, 5))
for(i in 1:2){
den[[i]] <- density(d[[i]])
f <- approxfun(den[[i]]$x, den[[i]]$y, yleft = 0, yright = 0) # how can it become loopable?
x[i] <- integrate(f, 0, .1)[[1]]
}
x
#[1] 0.001244482 0.110921241
Note the call to set.seed
, when using RNG's it is a good idea to set the seed, in order to have reproducible data and results.
Upvotes: 1
Reputation: 6222
In the following, class(f[1])
is a list
while class(f[[1]])
is a function
. So, you simply need to have f[[i]]
in the integrate
function.
den = list()
x = rep(0, 2)
d <- list()
d[[1]] <- rbeta(1e4, 5, 5)
d[[2]] <- rbeta(1e4, 2, 5)
f <- list()
for(i in 1:2){
den[[i]] <- density(d[[i]])
f[[i]] <- approxfun(den[[i]]$x, den[[i]]$y, yleft = 0, yright = 0)
x[i] <- integrate(f[[i]], 0, .1)[[1]]
}
Upvotes: 1