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

时间:2015-07-16 09:32:21

标签: r csv shiny

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

这是我的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

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

1 个答案:

答案 0 :(得分:1)

经过数千次试验和错误后,我找到了解决问题的方法。我做的是,我写了一个新的rscript文件,其中包含一个函数&#34; listfiles()&#34;返回包含文件所有名称的向量。在ui.R文件中,我添加了源(路径)函数来定位新的rscript文件,其中path是新脚本文件的路径。在selectInput()的下拉函数中,我只需要参数选择= 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文件,该函数返回我想要的值。

编辑后的更改

这是我的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=" ")
  })

}