user10401794
user10401794

Reputation:

Editing data frame after reactive upload in R shiny

I am trying to edit columns in a data frame yjay I uploadin using fileInput, however I keep getting the error "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.)". Does anybody know why I might be getting this error? Any help is greatly apprenticed!!

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)

Upvotes: 1

Views: 1515

Answers (1)

MrFlick
MrFlick

Reputation: 206232

The code in the server() function really should only set up reactive objects and respond to reactive events. You shouldn't have any data manipulation data in the body of the server() function itself because when that runs the data is not yet available. Something like this makes more sense

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)

Notice how a1 reads the file that the user uploads. Then the newdata reactive object will update whenever a1 updates and will transform the data for you. Then we can hook up that to an output so it will actually be processed.

Upvotes: 3

Related Questions