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

R/Shiny启动即报subscript out of bounds错误但R中运行正常

Seurat Shiny应用启动报"subscript out of bounds"错误原因及修复

错误触发原因

  • FeaturePlot() 函数的object参数要求传入Seurat S4对象实体,但代码中直接传入了input$celltype。Shiny的文本输入控件返回值是字符串类型(比如默认返回"MG"),不是全局环境中命名为MG的Seurat对象变量,Seurat内部访问对象数据槽时拿到字符串而非预期的S4对象,直接触发下标越界。
  • 应用启动时gene输入框默认值为空字符串"",Shiny的renderPlot会在应用启动瞬间立即执行,此时空字符串作为基因名传入,在表达矩阵中匹配不到对应基因,也会触发下标越界。
  • 代码存在笔误:RPE对象错误读取了CMZ.rds文件,后续选择RPE细胞类型时会加载错误数据集。
  • 原生R环境可正常运行是因为手动测试时直接传入了Seurat对象实体、真实存在的基因名,不存在传字符串对象名、空基因名的问题。

修复方案

  • 将所有Seurat数据集存入命名列表,通过输入的细胞类型字符串匹配取对应的实体对象
  • 增加输入合法性校验:基因名为空、输入细胞类型不在支持列表、基因不存在于当前数据集时,不执行绘图逻辑,返回友好提示
  • 修正RPE数据集读取的笔误

修复后的完整代码:

library(shiny)
library(Seurat)

# 修正RPE读错rds的笔误,将所有数据集存入命名列表方便索引
obj_list <- list(
  WholeEye = readRDS("WholeEye.rds"),
  MG = readRDS("MG.rds"),
  CMZ = readRDS("CMZ.rds"),
  RPE = readRDS("RPE.rds")
)

ui <- fluidPage(
  headerPanel('McFarlane scRNAseq'),
  sidebarPanel(
    textInput(inputId = 'celltype', label = "Choose a cell type. Eg. WholeEye, MG, RPE, CMZ", value = "MG", width = NULL, placeholder = NULL),
    textInput(inputId = 'gene', label = "Choose a gene", value = "", width = NULL, placeholder = NULL)
  ),
  mainPanel(
    plotOutput(outputId = "FeaturePlot" )
  )
)

server <- function(input, output) {
  output$FeaturePlot <- renderPlot({
    # 基础输入校验:细胞类型合法、基因名非空才继续执行
    req(input$celltype %in% names(obj_list), input$gene)
    current_obj <- obj_list[[input$celltype]]
    # 校验基因是否存在于当前数据集
    if (!input$gene %in% rownames(current_obj)) {
      plot.new()
      text(0.5, 0.5, "输入基因不存在于当前数据集,请检查基因名拼写", cex = 1.5)
      return()
    }
    # 传入实际的Seurat对象而非字符串
    FeaturePlot(object = current_obj, reduction = "umap", label = TRUE, min.cutoff = 0, features = input$gene)
  })
}

shinyApp(ui = ui, server = server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:48:19