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

R Shiny基于单列数据框创建selectInput下拉菜单失败问题求助

问题原因

selectInput组件的choices参数仅支持传入向量或命名列表,你当前传入了单列数据框,导致下拉选项无法正常渲染。

修复方案

只需修改唯一样本ID的提取逻辑,直接输出向量格式的唯一值即可,无需转换为数据框或多余的因子处理(如果有排序需求再转因子即可)。

修正后完整代码

library(shiny)
library(tidyverse) # 原代码用到了tibble、map等tidyverse生态函数,需要提前加载该包

# 读取样本文件
SpadeFiles <- dir("SampleDataFolder", recursive = TRUE, pattern = "*.csv", full.names = TRUE)  

SpadeData <- tibble(filename=SpadeFiles) %>%
  mutate(file_contents = map(filename,  ~ read_csv(.,skip=3,col_names = c("time", "torque"),
                                                   col_types = cols_only(col_double(),col_double(),col_skip(),col_skip()))))  

FullSpade <- unnest(SpadeData, cols = c(file_contents))     

FullSpade <- separate(FullSpade, filename,sep = "/",into = c("folder","sample_id"))    

# 核心修改:直接提取sample_id列的唯一值,输出为向量
UnqSI <- unique(FullSpade$sample_id)  

ui <- fluidPage(
  selectInput("ds", "请选择数据集:", choices = UnqSI),
  # 后续可添加绘图输出组件,例:plotOutput("torque_plot")
)

server <- function(input, output, session) {
  # 响应式筛选选中样本的对应数据,供后续绘图使用
  filtered_data <- reactive({
    FullSpade %>% filter(sample_id == input$ds)
  })
  
  # 绘图逻辑示例
  # output$torque_plot <- renderPlot({
  #   ggplot(filtered_data(), aes(x=time, y=torque)) + geom_line()
  # })
}

shinyApp(ui, server)

额外说明

如果需要固定下拉选项的显示顺序,可以在提取唯一值后自定义因子排序,示例:

UnqSI <- factor(unique(FullSpade$sample_id), levels = c("样本1.csv","样本2.csv"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:15:03