gpt4 book ai didi

r - 当一个值大于循环内的另一个值时停止循环函数

转载 作者:行者123 更新时间:2023-12-01 10:37:58 24 4
gpt4 key购买 nike

我一直在尝试编写一个 while 命令来在循环生成的一个值超过另一个值时停止循环函数。但是,我没有找到正确的方法。

for 循环运行 30 天,但我希望它在 parasite_l.A 的最后一个值小于 parasite_l 时立即停止。 B.

我已经包含了用于生成数据和 for 循环的工作代码。

不限制循环的替代解决方案也将不胜感激。

# Subject A, initially 400 parasites, growing by 10 %
subA = 400
infA = 1.1

# Subject B, initially 120 parasites, growing by 20 %
subB = 120
infB = 1.2

# How many days to model
days = 30

days_seq = seq(1, days, 1)

# Parasite load for A
parasite_l.A = rep(NA, days)
parasite_l.A[1] = subA

# Parasite load for B
parasite_l.B = rep(NA, days)
parasite_l.B[1] = subB

# Loop for subject A and B
for(i in 1:(days)){
parasite_l.A[i+1] = parasite_l.A[i]*(infA)
parasite_l.B[i+1] = parasite_l.B[i]*(infB)
}

parasite_l.A
parasite_l.B

最佳答案

对于您所指的名为while 的内容,有一个内置的控制流函数。只要满足条件就会一直循环下去。

i <- 1    
while (parasite_l.A[i] > parasite_l.B[i]) {
parasite_l.A[i+1] = parasite_l.A[i]*(infA)
parasite_l.B[i+1] = parasite_l.B[i]*(infB)
i <- i + 1
}

# parasite_l.A
# [1] 400.0000 440.0000 484.0000 532.4000 585.6400 644.2040 708.6244
# [8] 779.4868 857.4355 943.1791 1037.4970 1141.2467 1255.3714 1380.9085
# [15] 1518.9993 NA NA NA NA NA NA
# [22] NA NA NA NA NA NA NA
# [29] NA NA
# parasite_l.B
# [1] 120.0000 144.0000 172.8000 207.3600 248.8320 298.5984 358.3181
# [8] 429.9817 515.9780 619.1736 743.0084 891.6100 1069.9321 1283.9185
# [15] 1540.7022 NA NA NA NA NA NA
# [22] NA NA NA NA NA NA NA
# [29] NA NA

关于r - 当一个值大于循环内的另一个值时停止循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32509286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com