Home > Blockchain >  How to isolate a column of a reactive dataframe in R shiny in order to execute a math operation on i
How to isolate a column of a reactive dataframe in R shiny in order to execute a math operation on i

Time:08-03

In the below demo code I run a simple example of a reactive dataframe called choice1. I am trying to make a copy of choice1, called choice2, and simply multiply the right-most column (named "Values" in the data DF) of choice2 by a factor of 2. Choice1 renders correctly.

The below demo code almost works, except that when run the 2nd column of choice2 (named "Period" in choice1 and the data DF and should have the same name in choice2) doesn't render despite my including it in the cbind() below, and I also lose the column names leaving me with only V1 and V2 in the rendering of choice2. How do I resolve this? Also, is there a cleaner way to do this in base R? For now I'm avoiding other packages since I'm at this early stage just trying to learn R, Shiny, and reactivity.

Demo code:

library(shiny)

data <- 
  data.frame(
    ID = c(1,1,1,2,2,2),
    Period = c(1, 2, 3, 1, 2, 3),
    Values = c(5, 10, 15, 0, 2, 4)
  )

ui <- fluidPage(
  
  h5(strong("Base data frame:")), 
  tableOutput("data"),
  radioButtons(inputId = "showData",
               label = h5(strong("Show from original dataframe:")),
               choiceNames = c('All','First 4 rows'),
               choiceValues = c('All','Rows'),
               selected = 'All',
               inline = TRUE
              ),
  h5(strong("Reactive results:")), 
  tableOutput("choices1"),
  h5(strong("Mirrow results x 2:")), 
  tableOutput("choices2")
  )

server <- function(input, output, session) {
 
  output$data <- renderTable(data)
  
# reactiveValues is for multiple reactive values, whereas reactiveVal is for a single reactive value
  rv <- reactiveValues(choices1=c()) 
  observeEvent(input$showData, {
      if(input$showData == 'Rows'){rv$choices1 <- data[1:4,]} 
      else {rv$choices1 <- data}
      }
    )
  
  output[["choices1"]] <- renderTable({rv$choices1})

  output[["choices2"]] <- renderTable({cbind(rv$choices1[,1],rv$choices[,2],rv$choices1[,3] * 2)})
  
}

shinyApp(ui, server)

CodePudding user response:

You can do:

output[["choices2"]] <- renderTable({
  dat <- rv$choices
  dat[, 3] <- 2 * dat[, 3]
  dat
})
  • Related