在R Shiny中进行反应式上传后编辑数据帧

时间:2018-12-13 19:33:18

标签: r shiny shinydashboard shiny-reactivity

我试图编辑使用fileInput上传的数据框中的列,但是我不断收到错误消息:“如果没有活动的反应式上下文,则不允许进行操作。(您尝试做只能在反应式内部进行的操作表达式或观察者。)”。有人知道我为什么会收到此错误吗?任何帮助都是徒劳的!

server = function(input, output) {

  a1 = reactive({
    if(is.null(input$myFile$datapath)) NULL
    else{
      read_excel(input$myFile$datapath)
    }
  })


  x <- as.POSIXct(a1()$Month)

  a1()$mo <- strftime(x, "%m")
  a1()$yr <- strftime(x, "%Y")
  a1()$qrt <- quarter(x, with_year = FALSE, fiscal_start = 01)

  #subsetting data to display sales reps that hold a quota 

  newdata <- a1()[grepl("Y", a1()$`Quota Held Flag`),]

  #fixing participation column into categorical for donut chart
  newdata$Participation[is.na(newdata$Participation)] <- 0
  newdata$Participation <- factor(newdata$Participation, labels = 
                                    c("0-99%","100%")) 

  #grouping data
  newdata2 <- newdata %>%
    group_by(yr, mo, qrt) 
}
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

server()函数中的代码实际上仅应设置反应对象并响应反应事件。 server()函数本身不应包含任何数据处理数据,因为该数据在运行时尚不可用。这样的事情更有意义

ui <- fluidPage(
  fluidPage(
    titlePanel("Uploading Files"),
    fileInput('myFile', 'Choose File'),
    tableOutput('contents')
  )
)
server <- function(input, output) {

  a1 <- reactive({
    req(input$myFile)
    read_excel(input$myFile$datapath)
  })

  newdata <- reactive({
    a1 <- a1()
    x <- as.POSIXct(a1$Month)

    a1$mo <- strftime(x, "%m")
    a1$yr <- strftime(x, "%Y")
    a1$qrt <- quarter(x, with_year = FALSE, fiscal_start = 01)

    newdata <- a1[grepl("Y", a1$`Quota Held Flag`),]

    #fixing participation column into categorical for donut chart
    newdata$Participation[is.na(newdata$Participation)] <- 0
    newdata$Participation <- factor(newdata$Participation, labels = c("0-99%","100%")) 

    #grouping data
    newdata %>%
      group_by(yr, mo, qrt)     
  })

  output$contents <- renderTable(        
    newdata()        
  )

}
shinyApp(ui = ui, server = server)

请注意a1如何读取用户上传的文件。然后,newdata反应对象将在a1更新时更新,并为您转换数据。然后,我们可以将其连接到输出,以便对其进行实际处理。