I'm writing an online table by Shiny of R language, but something confusing stops me.
What I need is:
- Show the full table for the first time.
- If you type a number in the input block and submit, just show the top n rows of the table automatically.
What I see is:
DFflt
, the variable behind the table, is already changed after submission, but the table on the webpage cannot be reloaded before you refresh the page manually.
What can I do to solve this problem? Thanks!
library(shiny)
library(tidyverse)
DF <- mpg
DFflt <- mpg
ui <- fluidPage(
numericInput("nrow", "Slice the top n rows of DF", value = 0),
actionButton("submit", "Submit"),
actionButton("p_DFflt", "print DFflt in console"),
div('render DFflt:'),
tableOutput("table")
)
server <- function(input, output, session) {
observeEvent(input$submit, {
nrow <- input$nrow
if (nrow > 10) {
showNotification(str_c("Invalid", type="error")) }
else { DFflt <<- DF %>% head(nrow) }
})
observeEvent(input$p_DFflt, { print(DFflt)} )
output$table <- renderTable({DFflt})
}
shinyApp(ui, server)
CodePudding user response:
This should work as you expected:
library(shiny)
library(tidyverse)
DF <- mpg
ui <- fluidPage(
numericInput("nrow", "Slice the top n rows of DF", value = 0),
actionButton("submit", "Submit"),
actionButton("p_DFflt", "print DFflt in console"),
div('render DFflt:'),
tableOutput("table")
)
server <- function(input, output, session) {
n_row <- eventReactive(input$submit, {
input$nrow
})
observe({
if (n_row() > 10) {
showNotification(str_c("Invalid ", type="error"))
}
})
output$table <- renderTable({
if(input$submit == 0){ # when the submit button is not clicked
DF
}else{
if (n_row() >= 0 & n_row() <= 10) {
DF %>% head(n_row())
}
}
})
observeEvent(input$p_DFflt, { print(DF)} )
}
shinyApp(ui, server)