如何根据闪亮R上的用户信息使用actionButton对数据框进行子集化

时间:2017-09-04 17:41:21

标签: r shiny

我喜欢运行一大块代码而不是基于在闪亮UI上选择的输入来执行子集。

为了执行此操作,我尝试了不同的方法,但没有运气:

我想在UI中做这样的事情:

ui = navbarPage(title = 'panel',
            fluidPage(
              fluidRow(
                column(2,
                       selectInput('a', label = "choose",
                                   choices = unique(df$a)),
                       sliderInput(
                         'b', label = 'choose range:',
                         min = 5, max = 8, value = c(6,7)),
                       actionButton('click','click')),
column(5,
      tableOutput('table')))))

在服务器上有类似的东西

server = function(input,output){
                  df= data.frame(a = c(1,2,3,4), b = c(5,6,7,8))

  observeEvent(input$click,{
               df_ =  subset(df,  
               a == input$a & 
               b %in% input$b[1]:input$b[2])
               }) 

  input$table = renderDataTable({
  df_
  })
  }

运行此代码将我带到这个错误:

 shinyApp(ui, server)

 Warning: Error in $<-.reactivevalues: Attempted to assign value to a read-
 only reactivevalues object
 Stack trace (innermost first):
 47: $<-.reactivevalues
 46: $<- [#11]
 45: server [#11]
 4: <Anonymous>
 3: do.call
 2: print.shiny.appobj
 1: <Promise>
 Error in `$<-.reactivevalues`(`*tmp*`, "table", value = structure(function 
 (...)  : 
 Attempted to assign value to a read-only reactivevalues object

我认为我错过了一些具有反应值的重要事物,但我迷失了,因为我是新的闪亮的。我已经尝试了一些反应性按钮的例子,例如Rstudio提供但没有运气的按钮。

1 个答案:

答案 0 :(得分:0)

也许我们需要将input$table更改为output$table,并在'ui'中使用DT::dataTableOutput('table')

library(shiny)
library(DT
fsel <- function(dat) {

ui = navbarPage(title = 'panel',
                fluidPage(
                  fluidRow(
                    column(2,
                           selectInput('a', label = "choose",
                                       choices = unique(dat$a), selected = unique(dat$a)[1]),
                           sliderInput(
                             'b', label = 'choose range:',
                             min = 5, max = 8, value = c(6,7)),
                           actionButton('click','click')),
                    column(5,
                           DT::dataTableOutput('table')))))


server = function(input,output){


  rs <- reactiveValues()


  rs$df <- dat
  observeEvent(input$click,{
  df_ <-  subset(dat,  
                  a == input$a & 
                    b %in% input$b[1]:input$b[2])
  rs$df <- df_
  }) 

  output$table = renderDataTable({

    DT::datatable(rs$df)

  })
}
shinyApp(ui = ui, server = server) 
}

-data

df <- data.frame(a = sample(letters[1:3], 10, replace = TRUE), 
               b =1:10, stringsAsFactors = FALSE)

- 运行应用

fsel(df)

-output enter image description here

enter image description here