如何使用 rscript 代码填充 shiny ui.R 中的下拉菜单?

How to populate drop down menu in shiny's ui.R using rscript code?

我的一个目录中有一些 .csv 文件,想在 ui.R 中读取它们以填充下拉列表的选择参数。但我无法这样做。我已经提到了这些链接,但它们似乎对我没有帮助。

这是我的 ui.R

代码
library(shiny)


ui <- fluidPage(
  #this is where I start with my normal rscript code
  #I don't know even if this is allowed but shiny does
  #not give me any error in the source code
  files <- Sys.glob("/home/ubuntu/r-stockPrediction-master/input/*.csv"),
  selection = c(),
  for(i in 1:length(files)){
    selection[i] = strsplit(strsplit(files[i],"/")[[1]][6],".csv")
  },
  selectInput("choice","Select your choice",choices=selection),

  verbatimTextOutput("text")
)

这是我的 server.R

代码
library(shiny)


server <- function(input,output){
  output$text <- renderPrint({
    paste("you selected",input$choice,sep=" ")
  })

}

当我 运行 我的服务器时,浏览器页面显示

ERROR: object 'selection' not found

希望我已经提供了所有相关信息。如果您需要任何进一步的信息,请随时询问。提前谢谢你。

经过数千次尝试和错误,我找到了解决问题的方法。我所做的是,我编写了一个新的 rscript 文件,其中包含一个函数 "listfiles()" 到 return 一个包含所有文件名称的向量。在 ui.R 文件中,我添加了 source(path) 函数来定位新的 rscript 文件,其中 path 是新脚本文件的路径。在 selectInput() 的下拉函数中,我简单地设置了参数 choices = listfiles(),它就像魔术一样工作。请参阅下面的代码以便更好地理解。

这是我的listfiles.R脚本

    listfiles <- function(){

    files <- Sys.glob("/home/ubuntu/r-stockPrediction-master/input/*.csv")

    l = list()
    for(i in 1:length(files)){
      l[[i]] = strsplit(strsplit(files[i],"/")[[1]][6],".csv")
    }

    vect = c()
    for(i in 1:length(files)){
      vect[i] = l[[i]][[1]][1]     
    }
    return (vect)
  }

这是我的 ui.R 文件

library(shiny)
source("listfiles.R")

ui <- fluidPage(

  selectInput("choice","Select your choice",choices = listfiles()),

  verbatimTextOutput("text")
)

未对 server.R 文件进行任何更改。这行得通。我想,现在每当我需要将一些自动化任务包含在闪亮的脚本中时,我都会制作包含所需功能的外部 rscript 文件,returns 是我想要的值。

编辑后的变化

这是我的 ui.R 文件

library(shiny)
source("listfiles.R")

ui <- fluidPage(

  uiOutput("stocknames"),

  verbatimTextOutput("text")
)

这是我的 server.R 文件

library(shiny)
source("listfiles.R")

server <- function(input,output){

  stock_names <- reactive({
    return(listfiles())
  })
  output$stocknames <- renderUI({
    selectInput("choices","Select your choice",choices = as.vector(stock_names()))
  })


  output$text <- renderPrint({
    paste("you selected",input$choices,sep=" ")
  })

}