在闪亮的Web应用程序中根据用户输入选择特定的csv文件

时间:2018-01-09 10:53:59

标签: shiny shiny-server shinydashboard shinyjs

我有一个书名下拉列表,用户可以在其中选择所需的书名。 ui.R中的代码看起来像

selectInput(‘x’, label = ‘Choose the book’, choices = c(‘book1_name’,
‘book2_name’,
‘book3_name’),
selected = ‘book1_name’)

在我的应用程序文件夹中,每本书都有两个csv文件。我想根据下拉菜单中的用户选择,读取两个变量中相应的两个csv文件。类似的东西:

if(input$x==‘book1_name’){
data1<- read.csv(‘1_1.csv’)
data2 <- read.csv(‘1_2.csv’)
}
else if{
  (input$x==‘book2_name’){
    data1<- read.csv(‘2_1.csv’)
    data2 <- read.csv(‘2_2.csv’)

}

然后使用data1和data2进行进一步的计算。 什么应该是我在server.R中的代码 我尝试使用eventReactive,但无法设法获得正确的脚本。

1 个答案:

答案 0 :(得分:1)

您没有提供可重现的示例,因此我使用了mtcarsiris数据集。您可以在全局环境中读取自己的数据集。为了示例,我使用renderPlot函数向您展示它的工作原理。以下是两条建议:

选项1:

library(shiny)
library(tidyr)

ui = pageWithSidebar(
  headerPanel('testing'),
  sidebarPanel(
    selectInput('x', label = 'Choose the book', choices = c('book1_name', 'book2_name'), selected = 'book1_name')
  ),
  mainPanel(
    plotOutput('plot1')
  )
)

  server = function(input, output) {


    output$plot1 <- renderPlot({


      if (input$x == 'book1_name') {
        data1 <- iris
        data2 <- mtcars
        rownames(data2) <- NULL

        data1a <- data1[, 1:2]
        data2a <- data2[, 1:2]

        par(mfrow = c(1, 2)) 
        plot(data1a) #
        plot(data2a)  #
      } 

      if (input$x == 'book2_name') {
        data1 <- mtcars
        data2 <- iris
       # rownames(data2) <- NULL

        data1a <- data1[, 1:2]
        data2a <- data2[, 1:2]

        par(mfrow = c(1, 2)) 
        plot(data1a) #
        plot(data2a)  #
      } 


    })

  }

  shinyApp(ui = ui, server = server)

使用选项1,您可以在渲染函数中选择数据集(可能是另一个计算)。

选项2:

library(shiny)

ui = pageWithSidebar(
  headerPanel('testing'),
  sidebarPanel(
    selectInput('x', label = 'Choose the book', choices = c('book1_name', 'book2_name'), selected = 'book1_name')
  ),
  mainPanel(
    plotOutput('plot1')
  )
)

server = function(input, output) {


  data1 <- reactive({
    if (input$x == 'book1_name') {
      data1 <- iris
    } else {
      data1 <- mtcars
    }
  })

  data2 <- reactive({
    if (input$x == 'book1_name') {
      data2 <- mtcars
    } else {
      data1 <- iris
    }
  })


  output$plot1 <- renderPlot({

    data1 <- data1()
    data2 <- data2()

      data1a <- data1[, 1:2]
      data2a <- data2[, 1:2]

      par(mfrow = c(1, 2)) 
      plot(data1a) #
      plot(data2a)  #


  })

}

shinyApp(ui = ui, server = server)

使用选项2,您可以在渲染功能之外选择数据集。

希望它有所帮助!

相关问题