r - r中基于个体的模拟
问题描述
我的编码问题最好通过首先描述我正在使用的系统和数据来解释。然后我会提出我的问题/问我的问题。
我正在尝试模拟种群中单个昆虫的生长和发育。发展主要受温度驱动。因此,发展是以“积热”来衡量的,即更多的热量等于更多的发展。但是,有一个温度,低于该温度就不会发生发展(“基础”)。
每只昆虫在发育过程中都会经历多个阶段,每个阶段都有一个独特的基础温度。
最后,从一个阶段推进到下一个阶段所需的热量因人而异。
好的,一些示例数据:
# df1: Hourly temperatures
df1 = data.frame(DateTime = seq(
from = as.POSIXct("1986-1-1 0:00"),
to = as.POSIXct("1986-1-8 23:00"),
by = "hour"))
temp = c(5,5,5,6,7,8,9,10,13,17,22,25,26,28,26,25,25,22,19,14,10,8,5,5)
df1$temp <- temp
# df2: Each row is an individual insect.
# s1_thresh is the number of degrees that need to accumulate for each
# individual to advance from stage 1 to stage 2.
df2 <- data.frame(id = c("A", "B", "C", "D", "E"),
s1_thresh = c(21.5, 25.1, 19.9, 20.4, 21.4))
# Stage-specific base temperatures below which no degrees accumulate
base_s1 <- 10.5 # base temp for stage 1
base_s2 <- 8.6 # base temp for stage 2
# Temperature accumulation above base_s1
df1$dd_s1 <- ifelse(temp >= base_s1, (temp - base_s1)/24, 0)
df1$cumdd_s1 <- cumsum(df1$dd_s1)
这是我的问题:由于热量需求的不均匀性,每个人都会在独立的时间过渡/推进阶段,当这种过渡发生时,我如何改变每个人的基础温度?这是 df1 中单个“A”的期望结果(某种)。
# Example for single individual:
# Individual "A" has s1_thresh of 21.5, so a shift to base_2 occurs on 1986-01-04 16:00:00, row 89
df1$dd_s2 <- ifelse(df1$cumdd_s1 > df2$s1_thresh[df2$id == "A"] & temp >= base_s2, (temp - base_s2)/24, 0)
df1$cumdd_s2 <- cumsum(df1$dd_s2)
我试图避免为每个人设置多个温度累积列,但重要的是要知道在有限的时间范围内为每个人累积的热量。
非常感谢您的宝贵时间!
解决方案
假设您只需要每个人的累积阶段 2 度天的向量:
# transformed temperatures series relative to stages
df1$temps_b1 <- pmax(df1$temp - base_s1, 0)
df1$temps_b2 <- pmax(df1$temp - base_s2, 0)
ddsum <- function(theid) {
in_stage1 <- cumsum(df1$temps_b1/24) < df2$s1_thresh[df2$id==theid]
s2_temp <- ifelse(in_stage1, 0, df1$temps_b2)
return(cumsum(s2_temp/24))
}
res<-as.data.frame(sapply(df2$id, FUN=ddsum))
names(res) <- df2$id
res
推荐阅读
- java - 在 Freemarker 中将 GergorianCalendar 日期转换为自定义日期格式
- c++ - 如何绘制一条显示 QGraphicsScene 边界的线?
- postgresql - postgresql:在 Fedora 上的身份验证失败
- python - python中字典最快的键类型是什么?元组,frozenset ...?
- vmware-clarity - 复选框树视图
- firebase - 实时信使移动应用的 Firebase 安全规则
- mysql - SQL 分组按位设置?
- python-3.x - 在 SQL Server 2017 上运行 python 文件
- javascript - Highcharts - 如何为每种类型的图形全局设置渐变主题?
- java - CXF 网络服务客户端 ObjectFactory