从闪亮的 R 列表中分配 selectInput 选项

时间:2021-03-21 00:59:39

标签: r shiny

我有问题!我有一个包含文件列表的目录(都具有相同的扩展名 .hist)。我想为所有这些文件绘制直方图(我可以做这部分),但我希望能够从闪亮的下拉菜单中选择任何直方图,而无需明确写入“选择”。也就是说,我希望选择是动态的,并且基于读入的 .hist 文件...

假设我有 5 个样本及其对应的 .hist 文件:

A.hist
B.hist
C.hist
D.hist
E.hist

首先加载我所有的 .hist 文件:

library(ggplot2)
library(shiny)

temp = list.files(pattern="*.hist")
for (i in 1:length(temp)) assign(temp[i], read.table(temp[i]))
myfiles = lapply(temp, read.table)

然后我想为每个 .hist 文件输出直方图:

plot_histogram <- function(x) {
  
  x <- ggplot(x, aes(V2, V5)) + geom_col() + xlim(0,500) + ylim(0,0.01)+
    ylab("Proportion") + xlab("Read Depth")
  
}

lapply(myfiles, plot_histogram)

但是,我想要一个闪亮的应用程序,我可以从我的所有样本(A、B、C、D 或 E)中进行选择,它会生成绘图。我不想明确声明 A, B, C, D, E 作为选项,因为 .hist 文件的数量可能会改变。该应用程序将在每次批量运行时下载 .hist 文件,因此我需要它遍历目录中存在的文件。

这是我所拥有的...

ui <- fluidPage(
  titlePanel("Histogram QC"),
  sidebarLayout(
    sidebarPanel(
      ##ISSUE IS HERE, I do not want to use choices = c("A.hist", "B.hist" etc)
       selectInput("histo", "Select sample",
                  choices = c()
      ),
    mainPanel(
      plotOutput("histograms")
  )
))
)

server <- function(input, output) {
  output$histograms <- renderPlot({ 
    ggplot(input$histo, aes(V2, V5)) + geom_col() + xlim(0,500) + ylim(0,0.01)+
      ylab("Proportion") + xlab("Read Depth") 
  })
}

shinyApp(ui = ui, server = server)

我希望 selectInput 接受来自 myfiles... 的所有选项,这相当于(A.hist、B.hist 等)而无需明确命名它们。这可能吗?!

1 个答案:

答案 0 :(得分:0)

我有一个解决方案...

library(ggplot2)
library(shiny)

#load in coverage.hist files
coverage_hist = list.files(pattern="*_coverage.hist")

#load as separate df objects
for (i in 1:length(coverage_hist)) assign(coverage_hist[i], read.table(coverage_hist[i]))

#load as list of dfs
hist_files = lapply(coverage_hist, read.table)

#Add names to list
names(hist_files) = coverage_hist

ui <- fluidPage(
  titlePanel("Histogram QC"),
  sidebarLayout(
    sidebarPanel(
      selectInput("histo", "Select sample",
                  choices = coverage_hist
      )),
      mainPanel(
        plotOutput("histograms")
      )
    ))

server <- function(input, output) {
  output$histograms <- renderPlot({ 
    ggplot(get(input$histo), aes(V2, V5)) + geom_col() + xlim(0,500) + ylim(0,0.01)+
      ylab("Proportion") + xlab("Read Depth") 
  })

#or using list
#output$histograms <- renderPlot({ 
   # ggplot(hist_files[[input$histo]], aes(V2, V5)) + geom_col() + xlim(0,500) + ylim(0,0.01)+
     # ylab("Proportion") + xlab("Read Depth") 
#  })

}

shinyApp(ui = ui, server = server)
相关问题