R Shiny App
Back to Index
- R examples here are generated by gpt-4.
Sum of two numbers
library(shiny)
# Define the user interface
ui <- fluidPage(
titlePanel("Reactive Example"),
sidebarLayout(
sidebarPanel(
numericInput("num1", "First number:", value = 0),
numericInput("num2", "Second number:", value = 0)
),
mainPanel(
textOutput("sum")
)
)
)
# Define the server logic
server <- function(input, output) {
# Create a reactive expression for the sum
sum_reactive <- reactive({
input$num1 + input$num2
})
# Display the sum
output$sum <- renderText({
paste("The sum is:", sum_reactive())
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Changing line
library(shiny)
library(ggplot2)
# Define the user interface
ui <- fluidPage(
titlePanel("Reactive Scatter Plot Example"),
sidebarLayout(
sidebarPanel(
selectInput("dataset",
"Select a dataset:",
choices = c("mtcars", "iris")),
uiOutput("xvar_selector"),
uiOutput("yvar_selector")
),
mainPanel(
plotOutput("scatter_plot")
)
)
)
# Define the server logic
server <- function(input, output) {
# Load the selected dataset
dataset_reactive <- reactive({
switch(input$dataset,
"mtcars" = mtcars,
"iris" = iris)
})
# Generate variable selectors based on the selected dataset
output$xvar_selector <- renderUI({
selectInput("xvar",
"Select x-axis variable:",
choices = colnames(dataset_reactive()))
})
output$yvar_selector <- renderUI({
selectInput("yvar",
"Select y-axis variable:",
choices = colnames(dataset_reactive()))
})
# Create the scatter plot
output$scatter_plot <- renderPlot({
# Check if both variables are selected
if (is.null(input$xvar) || is.null(input$yvar)) {
return(NULL)
}
# Create the plot using ggplot2
ggplot(dataset_reactive(), aes_string(x = input$xvar, y = input$yvar)) +
geom_point() +
labs(x = input$xvar, y = input$yvar)
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Text as input
library(shiny)
# Define the user interface
ui <- fluidPage(
titlePanel("Word Count Example"),
sidebarLayout(
sidebarPanel(
textAreaInput("user_text", "Enter your text:", rows = 5, width = "100%"),
actionButton("count_button", "Count words")
),
mainPanel(
textOutput("word_count")
)
)
)
# Define the server logic
server <- function(input, output) {
# Count the number of words in the input text
count_words <- function(text) {
if (text == "") {
return(0)
} else {
words <- unlist(strsplit(text, "\\W+"))
return(length(words))
}
}
# Create a reactive value to store the word count
word_count <- reactiveVal(0)
# Update the word count when the button is clicked
observeEvent(input$count_button, {
word_count(count_words(input$user_text))
})
# Display the word count
output$word_count <- renderText({
paste("Number of words:", word_count())
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Text as input and output text
library(shiny)
# Define the user interface
ui <- fluidPage(
titlePanel("Reverse Text Example"),
sidebarLayout(
sidebarPanel(
textInput("user_text", "Enter your text:"),
actionButton("reverse_button", "Reverse text")
),
mainPanel(
textOutput("reversed_text")
)
)
)
# Define the server logic
server <- function(input, output) {
# Reverse the input text
reverse_text <- function(text) {
return(paste(rev(strsplit(text, "")[[1]]), collapse = ""))
}
# Create a reactive value to store the reversed text
reversed_text <- reactiveVal("")
# Update the reversed text when the button is clicked
observeEvent(input$reverse_button, {
reversed_text(reverse_text(input$user_text))
})
# Display the reversed text
output$reversed_text <- renderText({
reversed_text()
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Two text outputs
library(shiny)
# Define the user interface
ui <- fluidPage(
titlePanel("Text Manipulation Example"),
sidebarLayout(
sidebarPanel(
textInput("user_text", "Enter your text:"),
actionButton("process_button", "Process text")
),
mainPanel(
textOutput("reversed_text"),
textOutput("uppercase_text")
)
)
)
# Define the server logic
server <- function(input, output) {
# Reverse the input text
reverse_text <- function(text) {
return(paste(rev(strsplit(text, "")[[1]]), collapse = ""))
}
# Convert the input text to uppercase
uppercase_text <- function(text) {
return(toupper(text))
}
# Create reactive values to store the reversed and uppercase text
reversed_text_val <- reactiveVal("")
uppercase_text_val <- reactiveVal("")
# Update the reversed and uppercase text when the button is clicked
observeEvent(input$process_button, {
reversed_text_val(reverse_text(input$user_text))
uppercase_text_val(uppercase_text(input$user_text))
})
# Display the reversed text
output$reversed_text <- renderText({
paste("Reversed text:", reversed_text_val())
})
# Display the uppercase text
output$uppercase_text <- renderText({
paste("Uppercase text:", uppercase_text_val())
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Formating output and no reativeVal
- border: 2px solid #333; sets a 2-pixel-wide solid border with a color of #333 (dark gray).
- background-color: #f2f2f2; sets the background color of the container to a light gray.
- padding: 20px; adds 20 pixels of padding around the text inside the container.
- border-radius: 5px; adds rounded corners to the container with a 5-pixel radius.
library(shiny)
# Define the user interface
ui <- fluidPage(
titlePanel("Reverse Text Example"),
sidebarLayout(
sidebarPanel(
textInput("user_text", "Enter your text:")
),
mainPanel(
h3("Reversed text:"),
div(
id = "output-container",
textOutput("reversed_text"),
style = "border: 2px solid #333; background-color: #f2f2f2; padding: 20px; border-radius: 5px;"
)
)
)
)
# Define the server logic
server <- function(input, output) {
# Reverse the input text
reverse_text <- function(text) {
return(paste(rev(strsplit(text, "")[[1]]), collapse = ""))
}
# Display the reversed text directly from the input
output$reversed_text <- renderText({
reverse_text(input$user_text)
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Output both text and plot
library(shiny)
library(ggplot2)
# Define the user interface
ui <- fluidPage(
titlePanel("Text and Plot Example"),
sidebarLayout(
sidebarPanel(
numericInput("input_value", "Enter a value:", value = 1, min = 1)
),
mainPanel(
h3("Square of the input value:"),
textOutput("text_output"),
h3("Bar plot of the input value:"),
plotOutput("plot_output")
)
)
)
# Define the server logic
server <- function(input, output) {
# Compute the square of the input value
square_value <- function(value) {
return(value^2)
}
# Display the square of the input value as text
output$text_output <- renderText({
square_value(input$input_value)
})
# Display a bar plot of the input value
output$plot_output <- renderPlot({
data <- data.frame(value = input$input_value)
ggplot(data, aes(x = "Value", y = value)) +
geom_bar(stat = "identity", fill = "steelblue") +
ylim(0, max(10, input$input_value)) +
theme_minimal()
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
Adaptive input and output
library(shiny)
# Define the user interface
ui <- fluidPage(
titlePanel("Adaptive Input and Output Example"),
sidebarLayout(
sidebarPanel(
actionButton("add_input", "Add input field")
),
mainPanel(
div(id = "input_container"),
div(id = "output_container")
)
)
)
# Define the server logic
server <- function(input, output, session) {
# Counter to track the number of inputs
input_counter <- reactiveVal(0)
# Add an input field
observeEvent(input$add_input, {
input_counter(input_counter() + 1)
input_id <- paste0("input_value_", input_counter())
output_id <- paste0("output_value_", input_counter())
insertUI(
selector = "#input_container",
ui = tags$div(
id = paste0("div_", input_counter()),
numericInput(input_id, paste("Value", input_counter(), ":"), value = 1, min = 1)
)
)
insertUI(
selector = "#output_container",
ui = tags$div(
id = paste0("output_div_", input_counter()),
textOutput(output_id)
)
)
output[[output_id]] <- renderText({
input_value <- as.numeric(input[[input_id]])
square_value <- input_value^2
paste("Square of value", input_counter(), ":", square_value)
})
})
}
# Create the Shiny app
shinyApp(ui = ui, server = server)
R sessionInfo
R version 4.2.0 (2022-04-22) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 20.04.3 LTS
Matrix products: default BLAS: /usr/lib/x86_64-linux-gnu/atlas/libblas.so.3.10.3 LAPACK: /usr/lib/x86_64-linux-gnu/atlas/liblapack.so.3.10.3
locale: [1] LC_CTYPE=C.UTF-8 LC_NUMERIC=C LC_TIME=C.UTF-8
[4] LC_COLLATE=C.UTF-8 LC_MONETARY=C.UTF-8 LC_MESSAGES=C.UTF-8
[7] LC_PAPER=C.UTF-8 LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
attached base packages: [1] stats graphics grDevices utils datasets methods base
other attached packages: [1] Wu_0.0.0.9000 flexdashboard_0.6.1 lme4_1.1-31
[4] Matrix_1.5-3 mgcv_1.8-38 nlme_3.1-152
[7] png_0.1-8 scales_1.2.1 nnet_7.3-16
[10] labelled_2.10.0 kableExtra_1.3.4 plotly_4.10.1
[13] gridExtra_2.3 ggplot2_3.4.1 DT_0.27
[16] tableone_0.13.2 magrittr_2.0.3 lubridate_1.9.2
[19] dplyr_1.1.0 plyr_1.8.8 data.table_1.14.8
[22] rmdformats_1.0.4 knitr_1.42
loaded via a namespace (and not attached): [1] httr_1.4.5 sass_0.4.5 tidyr_1.3.0 jsonlite_1.8.4
[5] viridisLite_0.4.1 splines_4.2.0 bslib_0.4.2 assertthat_0.2.1 [9] yaml_2.3.7 pillar_1.8.1 lattice_0.20-45 glue_1.6.2
[13] digest_0.6.29 rvest_1.0.3 minqa_1.2.5 colorspace_2.1-0 [17] htmltools_0.5.4 survey_4.1-1 pkgconfig_2.0.3 haven_2.5.2
[21] bookdown_0.32 purrr_1.0.1 webshot_0.5.4 svglite_2.1.1
[25] timechange_0.2.0 tibble_3.1.8 generics_0.1.3 ellipsis_0.3.2
[29] cachem_1.0.6 withr_2.5.0 klippy_0.0.0.9500 lazyeval_0.2.2
[33] cli_3.6.0 survival_3.2-13 evaluate_0.20 fansi_1.0.4
[37] MASS_7.3-54 forcats_1.0.0 xml2_1.3.3 tools_4.2.0
[41] hms_1.1.2 mitools_2.4 lifecycle_1.0.3 stringr_1.5.0
[45] munsell_0.5.0 compiler_4.2.0 jquerylib_0.1.4 systemfonts_1.0.4 [49] rlang_1.1.1 grid_4.2.0 nloptr_2.0.3 rstudioapi_0.14
[53] htmlwidgets_1.5.4 rmarkdown_2.20 boot_1.3-28 gtable_0.3.1
[57] DBI_1.1.3 R6_2.5.1 fastmap_1.1.0 utf8_1.2.2
[61] stringi_1.7.12 Rcpp_1.0.10 vctrs_0.5.2 tidyselect_1.2.0 [65] xfun_0.37