R基于用户输入的闪亮子集,然后基于子集的代码

时间:2018-05-01 15:20:14

标签: r shiny

我尝试使用闪亮的服务器根据子集进行计算 - 称为sub1。 sub1正常工作,直到我尝试选择某个列或尝试对其进行计算。

sub1是大型数据集的子集。

附件是我的代码。让我知道我做错了什么。非常感谢你。

server <- function(input,output) {
  data1 <- read.csv("..",fileEncoding="UTF-8-BOM")

  sub1<- reactive(subset(data1,Sex == input$sex & AVS.Impairment == 
  input$impairment & Year == input$yr & Mortality <= max(input$mm) & Mortality 
  >= min(input$mm)))

  output$text<-renderDataTable(sub1())
  # I want to use the sub1 to run more calculation. 
  # But when I try to select the column and create column it won't work

   sub1$table = paste0(sub1$Sex) %>% tolower # this line doesn't work
   # error is object of type 'closure' is not subsettable

}

shinyApp(ui=ui, server=server)

1 个答案:

答案 0 :(得分:0)

我创建了一个可重现的示例,如果指定的代码我们取消注释,则会产生您提到的两个错误。您会注意到,当您第一次使用Shiny时,您遇到的错误与人们非常相似,所以这个答案并不新鲜。

# Show two errors that occur in Shiny.  
# 1. The error that occurs when you try to use and input$var outside of a reactive context
# 2. The error that occurs when you treat a reative function as an dataset instead of a function.

library(shiny)
library(lubridate)
d <- datasets::longley
# Create a date field for dateRangeInput
d$date <- as.Date(as.character(d$Year),"%Y")
# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Use of reactive in Shiny"),

   sidebarLayout(
      sidebarPanel(
        dateRangeInput("yr", h3("Date range"),
                       start = min(d$date),  
                       end = '1962-05-01'),
        sliderInput("mm","Minimum GNP", 500,min=min(d$GNP),
                     max=max(d$GNP))
     ),

      # Show a plot of the generated distribution
      mainPanel(
         textOutput("text"),
         textOutput("text_err"),
         dataTableOutput("table")

      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  sub1 <- reactive({
    subset(d,GNP <=input$mm & Year >= year(input$yr[[1]]) & Year <= year(input$yr[[2]]))
  })

  # Uncomment this will produce   
  # Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
  # sub2 <-   subset(d,GNP <=input$mm & Year >= year(input$yr[[1]]) & Year <= year(input$yr[[2]]))

  output$text <- renderPrint(paste(year(input$yr[[1]]),year(input$yr[[2]])))

  # This will generate the error Warning: Error in $: object of type 'closure' is not subsettable
  # output$text_err <- renderPrint(paste(sub1$Year))

  output$table <- renderDataTable(sub1())

}

# Run the application 
shinyApp(ui = ui, server = server)