Markus Hein
Markus Hein

Reputation: 63

Reactive Data, transforming and overwriting

I'm fairly new to R Shiny, and I'm having some problems with reactive Datasets.

My idea ist, to load a dataset, do some calculations on it, print the outcome. This is no Problem if I set the dataset as

df <- reactive({data.frame(mtcars)}) df_transformed <- reactive({data.frame(tapply(mt$hp, mt$cyl, mean), names(tapply(mt$hp, mt$cyl, mean))))}

but now i can't overwrite the initial dataset in a meaningful way. I searched through stack overflow a bit and only found howTos for one of these two problems, which kinda excluded each other.

I would like to have smth like this, but working:

 server <- function(input, output) {

  vals <- reactiveValues()

  ## Create a reactive value dataset
  vals$mt <- data.frame(mtcars)

  ## Create a transformed set out of it


  vals$mt_transformed <- data.frame(tapply(mt$hp, vals$mt$cyl, mean),
                                    names(tapply(vals$mt$hp, vals$mt$cyl, mean)))

  names(vals$mt_transformed) <- c("hp", "cyl")

  ## Transform the initial dataset, via deleting the last row
  observeEvent(input$delete, {
    vals$mt <- vals$mt[-nrow(vals$mt),]
    })

  ## lets hope the plot changes everytime I delete a car
  output$plot <- renderPlot({
    ggplot(vals$mt_transformed) +
      geom_bar(
        aes(x = cyl, y = hp ),
        stat = "identity"
      )
  })
  # 

}

and for completeness:

library(shiny)
library(ggplot2)
ui <- fluidPage(
  actionButton(inputId = "delete", label = "destroy car"),
  plotOutput("plot")

   )

Thank You in advance Markus

Upvotes: 1

Views: 172

Answers (1)

Markus Hein
Markus Hein

Reputation: 63

got it to work by myself.

server <- function(input, output) {

  vals <- reactiveValues()

  ## Create a reactive value dataset 
  vals$mt <- data.frame(mtcars)

  ## Create a transformed set out of it

  mt_transformed <- reactive({
          df <- vals$mt
          mt_transformed <- data.frame(tapply(df$hp, df$cyl, mean),
                  names(tapply(df$hp, df$cyl, mean)))
          names(mt_transformed) <- c("hp", "cyl")
          return( mt_transformed)
        })

  ## Transform the initial dataset, via deleting the last row
  observeEvent(input$delete, {
    vals$mt <- vals$mt[-nrow(vals$mt),]
    })

  ## lets hope the plot changes everytime I delete a car
  output$plot <- renderPlot({
    ggplot(mt_transformed()) +
      geom_bar( aes(x = cyl, y = hp ), stat = "identity" )
    }) 

}

Upvotes: 2

Related Questions