4.2 Reactivitiy()
4.2.2 reactiveValue()
This function returns an object to store reactive values. It is similar to a list but has special reactive programming capabilities. When you read a value from it, the calling reactive expression inherits a reactive dependency on that value, and when you write to it, it notifies all reactive functions that depend on that value. Note that values coming from the reactiveValues object are reactive, but the reactiveValues object itself is not.
# stored plot into reactiveValues
values <- reactiveValues(plot = NULL)
# get variable from the user "Select Variable"
var <- dt()[, input$var_plot]
if (is.numeric(var)) {
p <-
ggplot() + geom_histogram(
aes(x = var, fill = ..count..),
bins = 30,
position = "identity",
color = "white",
alpha = 1
) +
scale_fill_gradient(low = "lightgray",
high = "black",
guide = FALSE) +
labs(
x = input$var_plot,
y = "Count",
title = paste0("Histogram of ", input$var_plot, " (", input$dt, ")")
) +
theme_minimal() + theme(plot.title = element_text(
color = "gray",
size = 22,
face = "bold.italic"
))
} else{
p <-
ggplot() + geom_bar(
aes(x = as.factor(var)),
stat = "count",
group = 1,
fill = c(rep("lightgray", length(unique(
var
)) - 1), "#ff7b7b")
) +
geom_text(
stat = 'count',
aes(x = var, label = ..count..),
vjust = 1.6,
color = "white",
size = 11
) +
labs(
x = input$var_plot,
y = "Count",
title = paste0("Bar Plot of ", input$var_plot, " (", input$dt, ")")
) +
theme_minimal() + theme(plot.title = element_text(
color = "gray",
size = 22,
face = "bold.italic"
))
}
# stored plot so we can reuse for download
values$plot <- p
4.2.3 observeEvent() & updateTabsetPanel()
An observeEvent object can be used to trigger a piece of code when an event occurs. It can state “Hey, if I do this, I want you to run the codes in it”.
This is an example of the application. “Hey, when I click the submit button for the plot, the Plot tab is selected”. In the following codes below, I called the input$submit
, then it triggered updateTabsetPanel()
to update the tab plot_tab
# when the user click the submit button
# all of events in codes chunk run
observeEvent(input$submit, {
# Updated the Tab Panel, when the user click plot, it will jump to Plot tab
updateTabsetPanel(session, "tab_id", selected = "plot_tab")
})
# Create tab Panel
tabsetPanel(
id = "tab_id",
# Data Review tab will print out the data
tabPanel(
"Data Review",
value = "data_tab",
br(),
br(),
DT::DTOutput("dtable"),
br(),
br()
),
# Plot tab will print out the plot
tabPanel(
"Plot",
value = "plot_tab",
br(),
br(),
plotOutput("plot_out", width = "70%", height = "550px"),
br(),
uiOutput("dl_butt")
)
)