Reputation: 21
I'm trying to use two different set of lists as an input of a function using mapply, but I'm not sure how to. With the current code I have, it gives out an unexpected error. Did I use the mapply in a wrong way?
Here is a sample of the code:
t_index <- c("2022-01-01","2022-01-08","2022-01-15","2022-01-22","2022-01-29","2022-02-05","2022-02-12","2022-02-19",
"2022-02-26","2022-03-12","2022-03-26","2022-04-09","2022-04-23","2022-05-07","2022-05-21","2022-06-11")
t_index_day <- filter(flu2, Date %in% t_index)
t_index_day <- t_index_day$day
# SIR model
sir_1 <- function(alpha, beta, gamma, delta, S0, E0, I0, R0, D0, N, times) {
require(deSolve) # for the "ode" function
# the differential equations:
sir_equations <- function(time, variables, parameters) {
with(as.list(c(variables, parameters)), {
dS <- -beta * I * S/N
dE <- beta* I * S/N - (alpha*E)
dI <- alpha*E - (gamma*I) - (delta*I)
dR <- gamma * I
dD <- delta * I
return(list(c(dS, dE,dI, dR, dD)))
})
}
# the parameters values:
parameters_values <- c(alpha = alpha,beta = beta, gamma = gamma, delta = delta)
# the initial values of variables:===
initial_values <- c(S = S0, E=E0, I = I0, R = R0, D = D0)
# solving
out <- ode(initial_values, times, sir_equations, parameters_values)
# returning the output:
as.data.frame(out)
}
# sum of squares equation function for first
ss <- function(alpha,beta, gamma, delta, time, num, data = flu2, N = 50000000) {
print (num)
data = data[time[num]:time[num+1],]
E0 <-data$cases[1]*(alpha)
I0 <- data$cases[1]
R0 <- data$cases[1]*(gamma)
D0 <- data$deaths[1]
times <- data$day
predictions <- sir_1(alpha = alpha,beta = beta, gamma = gamma, delta = delta, # parameters
S0 = N - 639083, # cumulative case until now
E0 = E0,
I0 = I0,
R0 = R0,
D0 = D0,
N = N,
times = times) # time points
sum((predictions$I[-1] - data$cases[-1])^2)
}
loop <- as.integer(1:(length(t_index)-1))
beta_val <- seq(from = 0.1, to = 0.43, le = 300)
delta_val <- seq(from = 1/10000, to = 1/100, le = 300)
for (i in loop){
if (i == 1){
ss_val <- mapply(ss,beta_val, delta_val,alpha = 1/5, gamma = 1/7,time = t_index_day, num = i,data = flu2)
print(ss_val)
Error code:
Upvotes: 1
Views: 68
Reputation: 21
Then problem was with mapply trying to get all inputs as a part of a list, while I only wanted beta_val and delta_val as a part and the rest as a whole.
To solve this problem I changed the definition of the function ss:
ss <- function(alpha,beta, gamma, delta, time = t_index_day, num, data = flu2, N = 50000000) {
print (num)
data = data[time[num]:time[num+1],]
E0 <-data$cases[1]*(alpha)
I0 <- data$cases[1]
R0 <- data$cases[1]*(gamma)
D0 <- data$deaths[1]
times <- data$day
predictions <- sir_1(alpha = alpha,beta = beta, gamma = gamma, delta = delta, # parameters
S0 = N - 639083, # cumulative case until now
E0 = E0,
I0 = I0,
R0 = R0,
D0 = D0,
N = N,
times = times) # time points
sum((predictions$I[-1] - data$cases[-1])^2)
}
Upvotes: 1