【问题标题】:Individual-based simulation in rr中基于个体的模拟
【发布时间】:2018-08-29 20:00:30
【问题描述】:

首先描述我正在使用的系统和数据可以最好地解释我的编码问题。然后我会提出我的问题/提出我的问题。

我正在尝试模拟种群中单个昆虫的生长和发育。发展主要受温度驱动。因此,发展是以“积热”来衡量的,即更多的热量等于更多的发展。然而,有一个温度,低于这个温度就不会发生发展(“基础”)。

每一种昆虫在发育过程中都会经历多个阶段,每个阶段都有一个独特的基础温度。

最后,从一个阶段推进到下一个阶段所需的热量因人而异。

好的,一些示例数据:

# 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)

我试图避免为每个人设置多个温度累积列,但重要的是要知道每个人在有限的时间范围内累积的热量。

非常感谢您的宝贵时间!

【问题讨论】:

    标签: r simulation


    【解决方案1】:

    假设您只需要每个人的累积阶段 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
    

    【讨论】:

    • 谢谢@dschwilk!这很好用,正是我所要求的。最后一个问题:你能解释一下 [df2$id==theid] 和 function(theid) 是如何相关的吗?那里发生了什么?
    • 我继续在我的示例中使用了您的全局对象 (df1, df2)。因此, df2$s1_thresh[df2$id==theid] 只是将 df2 用作字典或地图对象。我根据 id 列过滤了 s1_thresh 列。该代码假定 id 是唯一的(如果不是,您将只获得第一个的阈值)。函数定义只允许我们将两个步骤结合起来(确定个人所处的阶段,然后在我们可以传递给 sapply() 的单个函数中计算第 2 阶段的天数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多