You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R脚本运行报错:number of items to replace is not a multiple of replacement length

问题解决:number of items to replace is not a multiple of replacement length

错误原因

你定义的矩阵n是2行结构(对应"juvenils"和"adults"),但循环中给n[, t]赋值时生成了4个数值,而n[, t]仅能容纳2个值,长度不匹配导致报错。

修正后的代码

estodemog <- function(mida, tmax = 50, grafic = T) {
    S1 = 0.480 ##supervivència del primer any de vida (de volander a 1 any)
    S2 = 0.574 #supervivència del segon any de vida
    S3 = 0.574 #supervivència del tercer any de vida
    S4 = 0.889 #supervivència del quart any de vida
    Sa = 0.889 #supervivència posteriors
    F2 = 0.286 #fecunditat (volandersper femella) de las femelles de dos anys
    F3 = 0.400 #fecunditat amb 3 anys
    Fa = 1.129 #fecunditat amb 4 o més anys
    Sr = 0.5 #quocient sexual (sex ratio)
    R2 = 0.161 #taxa de reclutament amb dos anys d’edat
    R3 = 0.680 #taxa de reclutament amb tres anys d’edat
    R4 = 0.934 #taxa de reclutament amb quatre anys d’edat
    n <- matrix(rep(0, tmax * 2), ncol = tmax)
    n[, 1] <- c(round(mida * 0.3), round(mida * 0.7))
    rownames(n) <- c("juvenils", "adults")
    for (t in 2:tmax) {
      n[, t] <- c(
        # 新幼体数量:各年龄成体繁殖贡献之和
        rbinom(1, n[1 , t - 1], S2 * R2 * F2 * Sr) +
          rbinom(1, n[2 , t - 1], S3 * R3 * F3 * Sr) +
          rbinom(1, n[2 , t - 1], Sa * R4 * Fa * Sr) +
          rbinom(1, n[2 , t - 1], Sa * Fa * Sr),
        # 新成体数量:幼体存活进入成体 + 原有成体存活
        rbinom(1, n[1 , t - 1], S2) + rbinom(1, n[1 , t - 1], S3) + rbinom(1, n[1 , t - 1], S4) +
          rbinom(1, n[2 , t - 1], Sa)
      )
      if (sum(n[, t]) == 0)
        break
    }
    if (grafic) {
      # 若matplot2报错,需先安装加载gplots包
      # install.packages("gplots")
      # library(gplots)
      matplot2(n, lty = 1, lwd = 4, col = c("blue", "red"))
    }
    return(t)
  }

estodemog(50)

补充说明

  • 核心修正:将成体更新的多个rbinom结果合并为一个值,确保n[, t]仅接收2个元素(对应幼体和成体),匹配矩阵的行结构。
  • 若运行时matplot2提示函数不存在,需先安装并加载gplots包,代码中已添加注释说明操作步骤。

内容的提问来源于stack exchange,提问作者Mcespecu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 07:15:08