我已经编写了一个简单的数值示例(稍后我将使其更加复杂).你有两种物质A和B.在每一轮(即一个过程的迭代)中,它们以r的速率相互消耗. 我有一些东西是有效的(见下面的介绍),但它相当难看.首先,它显式地依赖于一个循环(也许有一个使用MAP的解决方案),然后有两个变量包含初始状态,它们被覆盖.
最后,还有100条:物质A和B不能取负值,所以一旦出现负值,这个过程就必须停止. 请看邮件末尾的复印件. 任何改进建议都是受欢迎的.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
A <- 2000
B <- 1000 ## initial quantities of A and B
r <- 1/10 ## consumption rate
n_rounds <- 10 ## how many iterations
consumption_round <- function(ab_vec,r){ ## function determining how much
## A and B decreas at each round
A1 <- ab_vec[1]-ab_vec[2]*r
B1 <- ab_vec[2]-ab_vec[1]*r
res <- c(A1, B1)
return(res)
}
AB <- c(A,B) ## initial state
ini <- AB
list_res <- AB ## other variables storing the initial state which will be overwritten ## I would like a better way to do this
for (i in seq(n_rounds)){
print("i is,")
print(i)
output <- consumption_round(ini, r)
ini <- output
list_res <- rbind(list_res, output)
}
#> [1] "i is,"
#> [1] 1
#> [1] "i is,"
#> [1] 2
#> [1] "i is,"
#> [1] 3
#> [1] "i is,"
#> [1] 4
#> [1] "i is,"
#> [1] 5
#> [1] "i is,"
#> [1] 6
#> [1] "i is,"
#> [1] 7
#> [1] "i is,"
#> [1] 8
#> [1] "i is,"
#> [1] 9
#> [1] "i is,"
#> [1] 10
sim_res <- list_res |>
as_tibble(.name_repair="unique") |>
rename("A"="...1",
"B"="...2") |>
mutate(B=if_else(B>=0, B, 0)) |> ## B cannot be negative
slice(1:min(which(B==0))) ## As soon as B is zero, the simulation ends.
#> New names:
#> • `` -> `...1`
#> • `` -> `...2`
sim_res
#> # A tibble: 7 × 2
#> A B
#> <dbl> <dbl>
#> 1 2000 1000
#> 2 1900 800
#> 3 1820 610
#> 4 1759 428
#> 5 1716. 252.
#> 6 1691. 80.5
#> 7 1683. 0
创建于2024-01-18年第reprex v2.0.2页