繁体   English   中英

R基于用户输入的闪亮子集,然后基于该子集进行编码

[英]R shiny subset based on user-input and then code based on the subset

我尝试使用发亮的服务器基于称为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)

我创建了一个可重现的示例,如果指示的代码我们未加注释,则可能会产生您提到的两个错误。 您会注意到,第一次使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM