Read output from `verbatimTextOutput` into a data frame in Shiny

Viewed 152

How do I read the output from verbatimTextOutput into a data frame.

I want to be able to get a value from a submit button (here I have just used rnorm as the function that the submit button runs), and then read this calculated value into a data frame by pressing "Add".

My thinking was to save the output into a data frame, and then display that data frame. However something is going wrong and I'm unsure what.

For example:

library(shiny)
library(shinydashboard)

df <- NULL

ui <- dashboardPage(
  header = dashboardHeader(title = "Test"),
  
  sidebar = dashboardSidebar(),
  
  dashboardBody(
    fluidRow(
      column(12,
             numericInput(inputId = "mean", label = "Number:", value = 4),
             submitButton(text = "Apply Changes"),
             verbatimTextOutput("value_no"),
             actionButton("add", "Add"),
             tableOutput("table")
      )) # close column, fluid row
  ) # close body
)

server <- function(input, output) {
  
  output$value_no <- renderText({
    rnorm(n = 1, mean = input$mean)
  })
  
  Data = reactive({
    if (input$add > 0) {
      df <- data.frame(rbind(df, x=output$value_no))
      return(list(df=df))
    }
  })
  
  output$table <- renderTable({
    data.frame(Data()$df)
  }, 'sanitize.text.function' = function(x){x}
  )
}

shinyApp(ui, server)

How can I read the output from the verbatimTextOutput object into a data frame?

Many thanks.

1 Answers

A slight modification of your UI and server logic. The main change is a reactive getter of the value given to verbatimTextOutput. This can then be used elsewhere more easily. Also changed the order of "Add" and "Apply Changes".

EDIT after comment: To allow data to change on button click, we combine reactiveValues with observeEvent. The latter will observe button click while the former makes the data.frame modifiable.

library(shiny)
library(shinydashboard)
# Make df modifiable
df <- reactiveValues(data=data.frame(y=NULL))
ui <- dashboardPage(
  header = dashboardHeader(title = "Test"),
  
  sidebar = dashboardSidebar(),
  
  dashboardBody(
    fluidRow(
      column(12,
             numericInput(inputId = "mean", label = "Number:", value = 4),
             verbatimTextOutput("value_no"),
             actionButton("add", "Add"),
             submitButton(text = "Apply Changes"),
             tableOutput("table")
      )) # close column, fluid row
  ) # close body
)

server <- function(input, output) {
  
  rnorm_gen <- reactive(
    rnorm(n = 1, mean = input$mean)
    
  )
  output$value_no <- renderText({
    rnorm_gen()
  })


output$table<-renderTable(df$data)
# observe button click, rbind based on condition
observeEvent(input$add,
               {
               
                 if (input$add > 0) {
                
                  df$data <- rbind(df$data, rnorm_gen())
                 }
               })

}

shinyApp(ui, server)
Related