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

R Studio与RKWard执行代码无报错但无法生成图表求助

问题排查与代码修复方案

核心问题:代码逻辑缺陷导致数据异常,无法生成有效图表

你的代码虽能“运行”,但存在多处逻辑错误,导致模拟输出的频率数据大量缺失或异常,最终ggplot2无法绘制出预期图表。以下是具体问题和修复方案:

1. 未定义recombination_step函数

代码中调用了recombination_step(freqs_after_drift, recombination_freqs),但从未实现该函数。实际运行时会抛出错误,可能你未注意控制台的报错信息。

  • 修复:要么实现重组逻辑(示例如下),要么暂时注释重组步骤直接使用漂移后的频率:
# 示例重组逻辑:根据重组率随机调整频率
recombination_step <- function(freqs, recomb_rates) {
  freqs + recomb_rates * (sample(freqs) - freqs)
}

# 或者暂时注释重组步骤
# freqs_after_recombination <- recombination_step(freqs_after_drift, recombination_freqs)
freqs_after_recombination <- freqs_after_drift

2. 选择系数与等位基因数量不匹配

selection_coefficients和fitness_costs长度为4,但模拟6或8个等位基因时,allele_freqs[gen-1,]长度为6/8,与长度4的fitness_scaled相乘会触发R的循环匹配规则,导致选择压力计算完全错误。

  • 修复:让选择系数长度与每个倍性对应的等位基因数量匹配,或修改逻辑为每个等位基因生成对应系数:
# 示例:为每个等位基因随机分配选择系数和适应度成本
fitness <- 1 - (sample(selection_coefficients, num_alleles, replace = TRUE) + environmental_effect) * 
  sample(fitness_costs, num_alleles, replace = TRUE)

3. 仅在突变发生时更新世代数据

模拟循环中,只有产生新等位基因时才会更新allele_freqs[gen,]和alleles_over_time[[gen]]。但突变率仅0.005,大部分世代无突变,导致这些世代的频率数据为NA,绘图时无有效数据点。

  • 修复:在突变判断块之外添加默认更新逻辑,确保每个世代都有数据:
# 在mutation代码块结束后添加:
if (length(new_alleles) == 0) {
  # 无突变时,沿用重组后的频率和原有等位基因
  allele_freqs[gen,] <- freqs_after_recombination
  alleles_over_time[[gen]] <- alleles
}

4. 参数定义行语法错误

ploidies <- c(2, 3, 4) # Set multiple ploidies extinction_threshold <- 10存在格式问题(未正确换行),可能导致extinction_threshold解析错误。

  • 修复:拆分两行定义:
ploidies <- c(2, 3, 4)  # Set multiple ploidies
extinction_threshold <- 10  # Set the extinction threshold

环境层面排查(代码修复后仍无图表时)

  • 检查图形设备:运行dev.new()后再执行print(plot),查看是否弹出绘图窗口。
  • 更新包版本:将ggplot2和tidyr更新至最新版,建议用tidyr::pivot_longer替代已软弃用的tidyr::gather:
df_freqs_long <- tidyr::pivot_longer(df_freqs, cols = -Generation, names_to = "Allele", values_to = "Frequency")
df_alleles_long <- tidyr::pivot_longer(df_alleles, cols = -Generation, names_to = "Allele", values_to = "AlleleID")
  • 排查包冲突:运行search()查看加载的包,确认无函数覆盖情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:08:13