Reputation: 457
I have a problem that is as follows: I have two dataframes (parameters
and amounts
).
> head(parameters)
Ka V1 V2 Q CL
1 5.960224 20.46632 90.48670 5.5 68.192196
2 1.176143 16.05779 132.44959 5.5 6.421357
3 1.324476 34.91569 42.96544 5.5 20.761933
4 2.649055 21.55833 111.89387 5.5 6.868612
5 1.495101 32.97900 140.82672 5.5 4.340567
6 2.807148 29.33883 206.71401 5.5 8.756406
>head(amounts)
Depot Central Peripheral
1 10 0 0
2 10 0 0
3 10 0 0
4 10 0 0
5 10 0 0
6 10 0 0
I would like to pass each row of parameters
& amounts
to a ODE-solver named ode
, part of the deSolve
package. I came with the following answer using a for
loop, it works fine, but it takes ages when the number of loops is high (i.e, more than 500 iterations). I would like to substitute the for
loop with an apply
-like function. This is the loop:
Central_concs <- vector()
for(i in 1:nrow(parameters)){
n_a <- names(amounts)
amounts_i <- as.numeric(amounts[i, ])
names(amounts_i) <- n_a
parameters_i <- parameters[i, ]
out <- ode(y = amounts_i, times = times, func = TwoComp, parms = parameters_i)
Central_concs <- cbind(Central_concs, out)
}
The name extraction and re-naming is just an issue with the ode
function, don't worry about it. TwoComp
, argument passed to ode
, is just a function containing the system of differential equations.
I have tried with apply, but I have been totally unsuccessful. Any help is appreciated.
Upvotes: 0
Views: 37
Reputation: 1999
Maybe something like this?
parameters_matrix <- as.matrix(parameters)
amoumts_matrix <- as.matrix(amounts)
myfun <- function(i){
ode(y = amounts_matrix[i, ], times = times, func = TwoComp, parms = parameters_matrix[i,])
}
sapply(X = 1:nrow(parameters), FUN = myfun)
Upvotes: 3
Reputation: 2435
Maybe something along these lines:
custom.ode <- function(i){
n_a <- names(amounts)
amounts_i <- as.numeric(amounts[i, ])
names(amounts_i) <- n_a
parameters_i <- parameters[i, ]
out <- ode(y = amounts_i, times = times, func = TwoComp, parms = parameters_i)
return(out)
}
Central_concs <- lapply(1:nrow(amounts), custom.ode)
Upvotes: 2