David_Cola
David_Cola

Reputation: 45

How do I replace a column in dataframe with a reactiveValue vector?

I have a dataframe (alldata), where I want to convert the column to new values based on a selectInput. It seems the only way to update a dataframe is with reactiveValues. So I take one column from the original dataset that I want to manipulate, use that to convert the values, but when I try reattaching the new vector/column (outputall$counterion) the final alldata() dataframe is not updated.

alldata<-reactive({rbind(chlorideframe(),nitrateframe(),bicarbonateframe(),sulfateframe())})

outputall<-reactiveValues()

observe({
    outputall$counterion<-data.frame(conc=c(), hours=c())
  })

observe({
    if(input$OCunits=="c/c0"){
      outputall$counterion<-alldata()$conc/2
    }
    if(input$OCunits=="mg/L"){
      outputall$counterion<-alldata()$conc*1
    }
    if(input$OCunits=="ug/L"){
      outputall$counterion<-alldata()$conc*1000
    }
    if(input$OCunits=="ng/L"){
      outputall$counterion<-alldata()$conc*1000000
    }
  })

reactive({alldata$conc<-outputall$counterion})

observeEvent(input$run_button, {
    output$Plot<-renderPlot(
      
      ggplot(alldata(), mapping=aes(x=hours, y=conc, color=Chemical)) +
        geom_point() + mytheme + ggtitle("Counter-Ion Concentration over Time")
    )
  })

I've also tried just hardcoding it in like

dat<-data.frame(hours=alldata$hours, conc=outputall$counterion)

but this gives me the error

Warning: Error in as.data.frame.default: cannot coerce class ‘c("reactiveExpr", "reactive", "function")’ to a data.frame

Surely there has to be some way to use the reactiveValues I've gotten in another dataframe?

Upvotes: 0

Views: 67

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

I haven't seen your data but this may help you:

server <- function(input, output, session) {
  
  outputall <- reactiveValues(counterion = 0)
  
  alldata <- reactive({
    rbind(chlorideframe(),nitrateframe(),bicarbonateframe(),sulfateframe())
  })
  
  observeEvent(input$OCunits,{
    req(alldata())
    
    if(input$OCunits=="c/c0"){
      outputall$counterion <- alldata()$conc/2
    }
    if(input$OCunits=="mg/L"){
      outputall$counterion <- alldata()$conc*1
    }
    if(input$OCunits=="ug/L"){
      outputall$counterion <- alldata()$conc*1000
    }
    if(input$OCunits=="ng/L"){
      outputall$counterion <- alldata()$conc*1000000
    }
  })

  processed_data <- eventReactive(input$run_button,{
    req(alldata())
    
    plot_data <- alldata()
    plot_data$conc <- outputall$counterion
    plot_data
  })
  
  output$Plot <- renderPlot(
    ggplot(processed_data(), mapping=aes(x=hours, y=conc, color=Chemical)) +
      geom_point() + mytheme + ggtitle("Counter-Ion Concentration over Time")
  )

}

Upvotes: 1

Related Questions