R,Shiny:使用selectInput()选择来创建数据框

时间:2015-05-17 21:07:15

标签: r shiny

这似乎应该是微不足道的,但我显然错过了一些东西。我想从selectInput()中选择用于创建数据框的选择。 selectInput()生成的字符输出似乎不能用作创建数据框的输入。我的ui.R和server.R代码如下。 df<-data.frame(input$select, header=TRUE)行不会产生预期的输出。在此先感谢您的帮助。

ui.R

library(shiny)

shinyUI(

  # Use a fluid Bootstrap layout
  fluidPage(    

    # Give the page a title
    titlePanel("Select Test Dataset"),

    # Generate a row with a sidebar
    sidebarLayout(      

      # Define the sidebar with one input
      sidebarPanel(
        selectInput("select", "Test Dataset", 
                    choices= list("Model Year 2011" = 'cars2011', "Model Year 2012" = 'cars2012'),selected='cars2011')

      ),

      # mainPanel Output
      mainPanel(
        verbatimTextOutput("value"),
        verbatimTextOutput("type"),
        dataTableOutput(outputId="data")
      )

    )
  )
)

server.R

library(AppliedPredictiveModeling)
data(FuelEconomy)



shinyServer(function(input, output) {

  output$value <- renderPrint({ input$select })
  output$type <- renderPrint({class(input$select)})

  output$data <- reactive({
    df <- data.frame(input$select, header=TRUE)
    head(df)
  })




})

2 个答案:

答案 0 :(得分:1)

在定义shiny::renderDataTable时,您应该使用shiny::reactive代替output$data

output$data <- renderDataTable({
    df <- data.frame(input$select, header=TRUE)
    head(df)
})

答案 1 :(得分:1)

使用switch语句将字符串转换为数据框名称似乎有效。

在server.R中插入:

数据集&lt; - reactive({      开关(输入$选择,     &#34; cars2011&#34; = cars2011,     &#34; cars2012&#34; =汽车2012)     })

然后使用head(dataset())输出数据,提供所需的结果。