Hello everyone,
I have tried to create a app with R shiny where the user can download a excel file and print an interactive graph, using plotly from R, with the selection of the x and y parameters from selectInput() function.
library(shiny)
library(rsconnect)
library(ggplot2)
library(plotly)
plotType ← function(data, x, y, type){
switch(type,
“Line” = ggplot(data, aes_string(x, y)) + geom_line(),
“Scatterplot” = ggplot(data, aes_string(x, y)) + geom_point()
)
}
ui ← fluidPage(
sidebarPanel(
# Input: select a file
fileInput(inputId = “file1”, label = “Choose CSV File”,
multiple = FALSE,
accept = c(“text/csv”,
“text/comma-separated-values, text/plain”,
“.csv”)
),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons(inputId ="sep", label = "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
radioButtons(inputId = "quote", label = "Quote",
choices = c(None = "",
"Double Quote" = '"',
"Single Quote" = "'"),
selected = '"'),
# Horizontal line
tags$hr(),
# Empty inputs - they will be updated after the data is uploaded
selectInput('xcol', 'X Variable', ""),
selectInput('ycol', 'Y Variable', "", selected = ""),
# Horizontal line
tags$hr(),
# Input: Select the type of graph
radioButtons(inputId ="graph", label = "Type of graph:",
choices = c("Line",
"Scatterplot"),
selected = "Line")),
mainPanel(
tabsetPanel( type = “tabs”,
tabPanel(
# App title
titlePanel(“Uploading Files”),
# Output: Data file
tableOutput(“contents”)
),
tabPanel(
titlePanel(“Plot”),
plotOutput(‘MyPlot’)
),
tabPanel(
titlePanel(“Summary Statistics”),
verbatimTextOutput(“summary”)
))))
server ← function(input, output, session) {
data ← reactive({
req(input$file1) # require that the input is available
df ← read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
choices = names(df), selected = names(df)[sapply(df, is.numeric)])
updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
choices = names(df), selected = names(df)[sapply(df, is.numeric)])
return(df)
})
output$contents ← renderTable({
data()
})
output$MyPlot ← renderPlotly({
x ← data()[, c(input$xcol, input$ycol)]
p ← plotType(x, input$xcol,
input$ycol,
input$graph)
p
})
# Generate a summary table of the data uploaded
output$summary ← renderPrint({
y ← data()
summary(y)
})
}
shinyApp(ui = ui, server = server)