Reputation: 3
Assume you have the following code
X = cbind(5,3,4)
func <- function(t){
return(X*t)
}
Then func(5) results in the vector (25,15,20)
Now I want to solve the three integrals int(5t,dt,0,5)
, int(3t,dt,0,5)
and int(4t,dt,0,5)
. Unfortunately, this does not work with
integrate(func,lower=0,upper=10)$value
Can someone help me how I can do this without a for loop?
Upvotes: 0
Views: 404
Reputation: 5003
OK now I understand.
you can define func to return a function somthing like this
func <- function(t){
function(v){v*t}
}
now func(5)
returns a function that multpies its argument with 5
t <- func(5)
t(5)
[1] 25
now to integrate the three functions you can use lapply
lapply(X,function(t){integrate(func(t),0,5)})
If more variables are needed you can change the code accordingly
func <- function(V,y,w){
function(t){1/V * pmax.int(-c, pmin.int((y-t)/V,c))*w}
}
only with the list do we need to trix around a bit. I am using the package purrr here to make a list of list each list containg one set of the different variables.
V = c(1,2,3) ;c = 2; y = c(5,6,7); w = c(8,9,10); z = c(8,10,11)
L <- list(V = V,y = y, w = w,z = z)
L2 <- L %>% transpose()
The final call of the lapply will then look like this.
lapply(L2,function(vars){integrate(func(vars$V,vars$y,vars$w),vars$y,vars$z)})
Upvotes: 2