I have a code for a simulated birth/death process. And would like to find a function which takes a simluted process and a state of that process and returns the amount of time the process spent in that state.
I think I can use parts of the code i already have like the vector "time" in the code in some way. But I can't see it. For example I would like to find a function time_in_state <- function(s,process). Where the process can be for example process1 <- bd_process(2, 10, 0, 100) and the state s=2. Then the function should return the amount of time process1 spent in state 2.
bd_process <- function(lambda, mu, initial_state = 0, steps = 500) {
time_now <- 0
state_now <- initial_state
time <- 0
state <- initial_state
for (i in 1:steps) {
if (state_now == 3) {
lambda_now <- 0
} else {
lambda_now <- lambda
}
if (state_now == 0) {
mu_now <- 0
} else {
mu_now <- mu
}
if (((mu_now + lambda_now )* runif(1)) < mu_now) {
state_now <- state_now - 1
} else {
state_now <- state_now + 1
}
time_now <- time_now + time_to_transition
time <- c(time, time_now)
state <- c(state, state_now)
}
list(tid = time, state = state, steps=steps)
}