Error: argument "expr" is missing, with no default - r

So I'm trying to make a dashboard in R Shiny where in the first tab, users can input their data in csv file. And in the second tab they will see the summary and plot of their data. In the sub-tab Plot, the users will have to choose xlabel and ylabel from the dataset columns an the Plot A will show the scatter plot of xlabel and y label.
ui <- dashboardPage(skin='red',
dashboardHeader(title = "Dashboard"),
## Sidebar content
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "dashboard"),
menuItem("Visualization", tabName = "viz",
menuSubItem("Summary",tabName="sum"),
menuSubItem("Plot",tabName = "plot")),
menuItem("Interpretation", tabName = "int")
) ),
## Body content
dashboardBody(
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidPage(titlePanel("DATA"),
fluidRow(
column(width=4,
fileInput("file1", "Input CSV file",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))),
column(width=2,checkboxInput("header", "Header", TRUE)),
column(width=2,radioButtons("sep","Separator",
choices = c(Comma=",",
Semicolon = ";",
Tab = "\t"),
selected = ",")),
column(width=2,radioButtons("quote", "Quote",
choices = c(None = "",
"Double Quote" = '"',
"Single Quote" = "'"),
selected = '"')),
column(width=2,radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head"))
),
tableOutput("contents")
)),
# Second tab content
tabItem(tabName = "sum",
box(
title="Summary",
status="primary",
solidHeader = TRUE,
width = "100%",
collapsible = TRUE,
verbatimTextOutput("summary")
)
),
tabItem(tabName="plot",
h2("Plot"),
fluidRow(
selectInput("sip","select",choices = 1:10),
selectInput("sila","anda",choices = 1:10)
),
fluidRow(
box(
title = "Plot A",
status= "primary",
solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plota",height="300px")
),
box(
title = "Plot B",
status= "primary",
solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plotb",height="300px"
)
)
)),
tabItem(tabName = "int",
h2("hello")
)
)
))
server <- function(input, output,session) {
output$contents <- renderTable({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
req(input$file1)
df <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
if(input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
output$summary <- renderPrint({
req(input$file1)
dataset<- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
summary(dataset)
})
output$plota <- renderPlot({
req(input$file1)
dataset<- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
updateSelectInput(session,"sip",label="label",choices=names(dataset))
updateSelectInput(session,"sila",label="label",choices = names(dataset))
plot(dataset[eventReactive(input$sip)],dataset[eventReactive(input$sila)],pch=19)
})
output$plotb <- renderPlot({
})
}
shinyApp(ui, server)
This is how the code looks like. When i run this program, it result in error: argument "expr" is missing, with no default. What is expr in this context?

You don't need to use eventReactive since renderPlot is a reactive expression, use only the input$..
Another problem is that you are trying to update the selectImput's inside the renderPlot, which is not going to work. You should update them with a different reactive expression, like a reactive() where you can also read the file instead of reading it multiple times. Below is your code modified to solve the problem and also reading the file only once inside a reactive expression.
library(shiny)
library(shinydashboard)
ui <- dashboardPage(skin='red',
dashboardHeader(title = "Dashboard"),
## Sidebar content
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "dashboard"),
menuItem("Visualization", tabName = "viz",
menuSubItem("Summary",tabName="sum"),
menuSubItem("Plot",tabName = "plot")),
menuItem("Interpretation", tabName = "int")
) ),
## Body content
dashboardBody(
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidPage(titlePanel("DATA"),
fluidRow(
column(width=4,
fileInput("file1", "Input CSV file",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))),
column(width=2,checkboxInput("header", "Header", TRUE)),
column(width=2,radioButtons("sep","Separator",
choices = c(Comma=",",
Semicolon = ";",
Tab = "\t"),
selected = ",")),
column(width=2,radioButtons("quote", "Quote",
choices = c(None = "",
"Double Quote" = '"',
"Single Quote" = "'"),
selected = '"')),
column(width=2,radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head"))
),
tableOutput("contents")
)),
# Second tab content
tabItem(tabName = "sum",
box(
title="Summary",
status="primary",
solidHeader = TRUE,
width = "100%",
collapsible = TRUE,
verbatimTextOutput("summary")
)
),
tabItem(tabName="plot",
h2("Plot"),
fluidRow(
selectInput("sip","select",choices = 1:10),
selectInput("sila","anda",choices = 1:10)
),
fluidRow(
box(
title = "Plot A",
status= "primary",
solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plota",height="300px")
),
box(
title = "Plot B",
status= "primary",
solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plotb",height="300px"
)
)
)),
tabItem(tabName = "int",
h2("hello")
)
)
))
server <- function(input, output,session) {
dataset <- reactive({
req(input$file1)
dat <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
updateSelectInput(session,"sip",choices=names(dat))
updateSelectInput(session,"sila",choices = names(dat))
dat
})
output$contents <- renderTable({
# input$file1 will be NULL initially. After the user selects
# and uploads a file, head of that data file by default,
# or all rows if selected, will be shown.
req(input$file1)
df <- dataset()
if(input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
output$summary <- renderPrint({
req(input$file1)
summary(dataset())
})
output$plota <- renderPlot({
plot(dataset()[[input$sip]],dataset()[[input$sila]],pch=19)
})
output$plotb <- renderPlot({
})
}
shinyApp(ui, server)

Related

How to fetch the dynamic slider values in r shiny app?

I stuck in printing dynamic slider values. In the following code I tried to print the dynamic slider values but it's not possible.
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Dynamic slider"),
dashboardSidebar(
tags$head(
tags$style(HTML('.skin-blue .main-sidebar {
background-color: #666666;
}'))
),
sidebarMenu(
menuItem("Input data", tabName = 'input_data')
),
fileInput(
"file",
"Choose CSV File",
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
checkboxInput("header",
"Header",
value = TRUE),
radioButtons(
"disp",
"Display",
choices = c(Head = "head",
All = "all"),
selected = "head"
),
sliderInput(
inputId = 'slr',
label = 'Slider range',
min = 0,
max = 3,
value = c(0.5,3),
step = 0.5
),
selectInput(
inputId = 'var',
label = 'Variables',
'Names',
multiple = TRUE
),
uiOutput('sliders')
),
dashboardBody(tabItems(
tabItem(tabName = 'input_data',
fluidRow(
box(width = 12,
dataTableOutput('table'),
title = 'Raw data'),
box(width = 6,
verbatimTextOutput('slider1'),
title = 'slider range'),
box(width = 6,
verbatimTextOutput('slider2'),
title = 'dynamic slider value')
)
)
))
)
server <- function(input, output) {
dataset <- reactive({
req(input$file)
read.csv(input$file$datapath,header = input$header)
})
observe(
output$table <- DT::renderDataTable({
if (input$disp == 'head') {
head(dataset())
}
else{
dataset()
}
})
)
observe({
updateSelectInput(inputId = 'var',choices = c(' ',names(dataset())))
})
variables <- reactive({
input$var
})
sli <- reactive({
lapply(1:length(variables()), function(i){
inputName <- variables()[i]
sliderInput(inputName, inputName,
min = 0, max = 1, value = c(0.3,0.7))
})
})
output$sliders <- renderUI({
do.call(tagList,sli())
})
output$slider1 <- renderPrint({
input$slr
})
output$slider2 <- renderPrint({
sli()
})
}
shinyApp(ui = ui, server = server)
Any suggestions will be appreciated, Is there any other method to get dynamic sliders based on selected variables or How can we get the values of the dynamic slider here??
There may be better ways to structure your app, but here is a solution that follows your general approach. There are 4 modifications to what you already have:
There is no need to define the reactive variables when you can just use input$var directly. The proposed solution eliminates this reactive.
Using req(input$var) will prevent components dependent on that selectInput from trying to render when a selection has not been made.
Since input$var defines the id of the dynamic slider, you can use this to retrieve the slider's values (i.e., input[[input$var]]).
Since you have specified "multiple = TRUE", a few nested paste statements are used to create a single string representing the values of all (potentially multiple) dynamic sliders.
The below app includes these modifications, and I believe, achieves what you are trying to accomplish.
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Dynamic slider"),
dashboardSidebar(
tags$head(
tags$style(HTML('.skin-blue .main-sidebar {
background-color: #666666;
}'))
),
sidebarMenu(
menuItem("Input data", tabName = 'input_data')
),
fileInput(
"file",
"Choose CSV File",
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
checkboxInput("header",
"Header",
value = TRUE),
radioButtons(
"disp",
"Display",
choices = c(Head = "head",
All = "all"),
selected = "head"
),
sliderInput(
inputId = 'slr',
label = 'Slider range',
min = 0,
max = 3,
value = c(0.5,3),
step = 0.5
),
selectInput(
inputId = 'var',
label = 'Variables',
'Names',
multiple = TRUE
),
uiOutput('sliders')
),
dashboardBody(tabItems(
tabItem(tabName = 'input_data',
fluidRow(
box(width = 12,
dataTableOutput('table'),
title = 'Raw data'),
box(width = 6,
verbatimTextOutput('slider1'),
title = 'slider range'),
box(width = 6,
verbatimTextOutput('slider2'),
title = 'dynamic slider value')
)
)
))
)
server <- function(input, output) {
dataset <- reactive({
req(input$file)
read.csv(input$file$datapath,header = input$header)
})
observe(
output$table <- DT::renderDataTable({
if (input$disp == 'head') {
head(dataset())
}
else{
dataset()
}
})
)
observe({
updateSelectInput(inputId = 'var',choices = c(' ',names(dataset())))
})
sli <- reactive({
lapply(1:length(input$var), function(i){
inputName <- input$var[i]
sliderInput(inputName, inputName,
min = 0, max = 1, value = c(0.3,0.7))
})
})
output$sliders <- renderUI({
req(input$var)
do.call(tagList,sli())
})
output$slider1 <- renderPrint({
input$slr
})
output$slider2 <- renderPrint({
req(input$var)
paste(
sapply(
input$var,
function(x) {
paste(x, paste(input[[x]], collapse = ', '), sep = ': ')
}
),
collapse = '; '
)
})
}
shinyApp(ui = ui, server = server)

Possible Reactive function for PDF download in Shiny

I'm wondering if it's possible to have a shiny app being able to download a PDF of selected table content.
For example, if I have two tables, and I select one table to be downloaded via PDF, it will download a PDF that has the title content I want and the specified table in a PDF format. Not sure how I can change the downloadHandler portion so that the PDF download works and not give me the following error:
Warning: Error in FUN: non-numeric argument to binary operator [No
stack trace available]
.
The code is as follows:
df1<- data.frame(c(1:4),c("Z","Y","X","A"))
df2<- data.frame(c("Apple","Orange"),c(6.99,4.99))
colnames(df1)<-c("Col1","Col2")
colnames(df2)<-c("ColA","ColB")
library(shiny)
library(Cairo)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title="Test"),
dashboardSidebar(sidebarMenu(
menuItem("Data Table", tabName = "dashboard", icon = icon("th")))),
dashboardBody(tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidRow(
box(downloadButton("download", "PDF Download"),
radioButtons(inputId="filter1", label="Table", choiceNames = c("One","Two"), choiceValues = c("df1","df2"),inline= TRUE))),
fluidRow(box(
column(8, align="center", offset = 2,tags$b(textOutput("text1"))),
br(),br(),br(),br(),
textOutput("text2"),
tableOutput("static1"),
width=12))
)))
)
server <- function(input, output) {
output$text1 <- renderText({ "This Table" })
output$text2 <- renderText({"PR"})
df02 <- reactive({
get(input$filter1)
})
output$static1 <- renderTable({
df02()
})
output$download <- downloadHandler(
filename = 'report.pdf',
content = function(file) {
cairo_pdf(filename = "file123.pdf",
df02())
}, contentType = "application/pdf"
)
}
shinyApp(ui, server)
It seems that the PDF download does not work. I want the downloaded PDF to look like this when I select Table One and click on the PDF download button:
I want the downloaded PDF to look like this when I select Table Two to be downloaded:
df1 <- data.frame(c(1:4), c("Z", "Y", "X", "A"))
df2 <- data.frame(c("Apple", "Orange"), c(6.99, 4.99))
colnames(df1) <- c("Col1", "Col2")
colnames(df2) <- c("ColA", "ColB")
library(shiny)
library(shinydashboard)
library(xtable)
library(withr)
library(shinybusy)
ui <- dashboardPage(
dashboardHeader(title = "Test"),
dashboardSidebar(sidebarMenu(
menuItem("Data Table", tabName = "dashboard", icon = icon("th"))
)),
dashboardBody(
add_busy_spinner(spin = "cube-grid", onstart = FALSE),
tabItems(
# First tab content
tabItem(
tabName = "dashboard",
fluidRow(
box(
downloadButton("download", "PDF Download"),
radioButtons(
inputId = "filter1", label = "Table", inline = TRUE,
choiceNames = c("One", "Two"), choiceValues = c("df1", "df2")
)
)
),
fluidRow(box(
column(8, align = "center", offset = 2, tags$b(textOutput("text1"))),
br(), br(), br(), br(),
textOutput("text2"),
tableOutput("static1"),
width = 12
))
)
)
)
)
server <- function(input, output) {
output$text1 <- renderText({
"This Table"
})
output$text2 <- renderText({
"PR"
})
df02 <- reactive({
get(input$filter1)
})
output$static1 <- renderTable({
df02()
})
output[["download"]] <- downloadHandler(
filename = "results_from_shiny.pdf",
content = function(file){
texfile <- paste0(tools::file_path_sans_ext(file), ".tex")
latex <- print.xtable(
xtable(df02()), print.results = FALSE,
floating = FALSE, scalebox = "0.9"
)
writeLines(
c(
"\\documentclass[12pt]{standalone}",
"\\usepackage{graphics}",
"\\usepackage{caption}",
"\\begin{document}",
"{\\large\\bf This table.}",
"",
"\\newline",
"",
"\\minipage{\\textwidth}",
"\\centering",
latex,
"\\captionof{table}{My caption}",
"\\endminipage",
"\\end{document}"
),
texfile
)
with_dir(
dirname(texfile),
tools::texi2pdf(texfile, clean = TRUE)
)
}, contentType = "application/pdf"
)
}
shinyApp(ui, server)
EDIT
Or you can use the capture package:
tabItem(
tabName = "dashboard",
fluidRow(
box(
capture::capture_pdf(
selector = "#table-container",
filename = "table.pdf",
icon("camera"), "Take screenshot of table."
),
radioButtons(
inputId = "filter1", label = "Table", , inline = TRUE,
choiceNames = c("One", "Two"), choiceValues = c("df1", "df2")
)
)
),
fluidRow(box(
id = "table-container",
column(8, align = "center", offset = 2, tags$b(textOutput("text1"))),
br(), br(), br(), br(),
textOutput("text2"),
tableOutput("static1"),
width = 12
))
)

R shinydashboard collapsible menuItem with inputs

I am trying to implement a fileInput using library(shinydashboard) to provide the user with the option to upload files (as it was done here with a basic shiny UI - please find the example code below).
I would like to place the fileInput in the dashboardSidebar in an expandable menuItem, but don't know where it should go into the shinydashboard structure.
library(shiny)
ui <- fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
radioButtons("quote", "Quote",
choices = c(None = "",
"Double Quote" = '"',
"Single Quote" = "'"),
selected = '"'),
tags$hr(),
radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head")
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output) {
output$contents <- renderTable({
req(input$file1)
df <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
if(input$disp == "head") {
return(head(df))
}
else {
return(df)
}
})
}
shinyApp(ui, server)
Edit: I cleaned up the code a little to make the difference between childfull and childless menuItem's more clear - the parameters expandedName and startExpanded can only be used with a childfull menuItem in contrast tabName and selected is only used with childless menuItem's.
library(shiny)
library(shinydashboard)
ui <- function(req) {
dashboardPage(
dashboardHeader(title = "Simple tabs"),
dashboardSidebar(sidebarMenu(
id = "sidebarItemSelected",
menuItem(
"Childfull menuItem",
menuItem(
"Childless menuItem 1",
tabName = "childlessTab1",
icon = icon("dashboard"),
selected = TRUE
),
fileInput("upload", "Upload"),
bookmarkButton(),
expandedName = "childfullMenuItem",
startExpanded = TRUE
),
menuItem(
"Childless menuItem 2",
icon = icon("th"),
tabName = "childlessTab2",
badgeLabel = "new",
badgeColor = "green"
)
)),
dashboardBody(tabItems(
tabItem(tabName = "childlessTab1",
h2("Dashboard tab content")),
tabItem(tabName = "childlessTab2",
h2("Widgets tab content"))
))
)
}
server <- function(input, output, session) {
observe({
cat(
paste(
"\nsidebarItemSelected:",
input$sidebarItemSelected,
"\nsidebarItemExpanded:",
input$sidebarItemExpanded,
"\nsidebarCollapsed:",
input$sidebarCollapsed,
"\n"
)
)
})
}
shinyApp(ui, server, enableBookmarking = "url")
Initial answer:
Sure - this is possible (modified version of this example):
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Simple tabs"),
dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", fileInput("upload", "Upload"), tabName = "dashboard", icon = icon("dashboard")),
menuItem("Widgets", icon = icon("th"), tabName = "widgets",
badgeLabel = "new", badgeColor = "green")
)
),
dashboardBody(
tabItems(
tabItem(tabName = "dashboard",
h2("Dashboard tab content")
),
tabItem(tabName = "widgets",
h2("Widgets tab content")
)
)
)
)
server <- function(input, output, session) {}
shinyApp(ui, server)

need help fixing shiny dashboard?

I recently started using Shiny and I need help with shiny dashboard errors. I am trying to build an app using Shiny Dashboard, But I keep getting errors: "Error in tagAssert(sidebar, type = "aside", class = "main-sidebar") :
object 'sidebar' not found"
Can Someone help me fix the error??
Thanks in Advance
library(shiny)
library(shinydashboard)
library(DT)
library(tidyverse)
library(plotly)
covid <- read.csv("covid.csv")
covid_deaths <- read.csv("COVID_DEATHS_UK.csv")
noncovid_deaths <- read.csv("NON_COVID_DEATHS_UK.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
function(request){
sidebar <- dashboardSidebar(
hr(),
sidebarMenu(id="tabs",
menuItem("Global COVID data",
menuSubItem("COVID vaccinations: Deaths Vs All variable", tabName = "Dashboard"),
selectInput("location", "1. Select a country",
choices = covid$location, selectize = TRUE, multiple = FALSE),
menuSubItem("Scatterplot", tabName = "Scatterplot", icon = icon("line-chart")),
menuSubItem("Regression", tabName = "Regression", icon = icon("cog")),
menuSubItem("Multicollinearity", tabName = "Multicollinearity", icon = icon("line-chart")),
menuSubItem("Summary", tabName = "Summary", icon = icon("file-o-text")),
menuSubItem("DataTable", tabName = "DataTable", icon = icon("table"), selected=TRUE)
),
menuItem("COVID_Deaths", tabName = "COVID Deaths", icon = icon("line-chart")),
menuItem("NonCOVID_Deaths", tabName = "Non COVID Deaths", icon = icon("line-chart"))
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "Scatterplot",
fluidRow(
column(width = 6,
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation")),
tabPanel(helpText("Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths"),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
))))),
tabItems(
tabItem(tabName = "Regression",
fluidRow(
column(width = 6,
tabPanel(verbatimTextOutput(outputId = "regsum"),
verbatimTextOutput(outputId = "indprint"),
verbatimTextOutput(outputId = "depprint")),
tabPanel(helpText("Select input for Independent variables"),
selectInput(inputId = "indvar", label = "Independent Variable", multiple = TRUE,
choices = list("total_cases", "total_vaccinations", "people_fully_vaccinated", "total_boosters","stringency_index",
"population_density", "aged_65_older","gdp_per_capita","extreme_poverty", "cardiovasc_death_rate", "diabetes_prevalence", "handwashing_facilities", "life_expectancy","human_development_index")),
helpText("Select input for dependent variables"),
selectInput(inputId = "depvar", label = "Dependent variable", multiple = FALSE,
choices = list("total_deaths","new_deaths","new_cases")))
)))),
tabItems(
tabItem(tabName = "Multicollinearity",
fluidRow(
tabPanel(img(src="Multicollinearity.png"))))),
tabItems(
tabItem(tabName = "Summary",
fluidRow(tabPanel(
verbatimTextOutput("summary")
)))),
tabItems(
tabItem(tabName = "DataTable",
fluidRow(tabPanel(DTOutput("dataset")),
tabPanel(helpText("Select the Download Format"),
radioButtons("type", "4. Format type:",
choices = c("Excel (csv)", "Text(tsv)", "Doc")),
br(),
helpText("Click on the download button to download dataset"),
downloadButton("downloadData", "Download"))))),
tabItems(tabItem(tabName = "COVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist1")),
tabPanel(helpText("Select Variables for a COVID deaths"),
selectInput(inputId = "Yaxis", label = "yaxis:",
choices = names(subset(covid_deaths, select = -c(Week_number,Week_ending)))))))),
tabItems(tabItem(tabName = "NonCOVID Deaths",
fluidRow(tabPanel(plotlyOutput("hist2")),
tabPanel(helpText("Select Variables for a NOn- COVID deaths"),
selectInput(inputId = "ya", label = "Yaxis:",
choices = names(subset(noncovid_deaths, select = -c(Week_number,Week_ending))))))))
)
}
ui <- dashboardPage(skin = "black",
dashboardHeader(title = title),
sidebar,body)
server <- function(input, output, session) {
output$location <- renderPrint({
locationfilter <- subset(covid, covid$location == input$location)
})
output$summary <- renderPrint({
summary(covid)
})
datasetinput <- reactive({covid})
fileExt <- reactive({
switch(input$type,
"Excel (csv)" = "csv", "Text (tsv)" = "tsv", "Doc" = "doc")
})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$downloadData <- downloadHandler(
filename = function(){
paste("covid", fileExt(),sep = ".")
},
content = function(file){
sep <- switch(input$type,
"Excel (csv)" = ",", "Text (tsv)" = "\t", "Doc" = " ")
write.table(datasetinput(), file, sep = sep, row.names = FALSE)
}
)
output$scatterplot <- renderPlotly({
#ggplot(subset(covid, covid$location == input$location),aes(y= input$y,x=input$x))+geom_point()
ggplotly(ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index"))
})
output$correlation <- renderText({
x <- covid[covid$location == input$location, input$x]
y <- covid[covid$location == input$location, input$y]
xy = data.frame(x,y)
xy = xy[complete.cases(xy),]
var(xy)
cor(xy,method = 'pearson')
})
output$hist1 <- renderPlotly({
ggplotly(ggplot(covid_deaths, aes(x=Week_number, y= .data[[input$Yaxis]]))+
geom_point()
)
})
output$hist2 <- renderPlotly({
ggplotly(ggplot(noncovid_deaths, aes(x=Week_number, y= .data[[input$ya]]))+
geom_point()
)
})
lm1 <- reactive({lm(reformulate(input$indvar, input$depvar), data = subset(covid, covid$location == input$location))})
output$depPrint <- renderPrint({input$depvar})
output$indPrint <- renderPrint({input$indvar})
output$regsum <- renderPrint({summary(lm1())})
}
# Shiny dashboard
shiny::shinyApp(ui, server)

Error while uploading a file using file input

I am trying to develop an application, that could help the users upload a file and display the summary statistics.
I am using the below UI and Server code to achieve this, once I have completed my file upload, i am unable to see the data frame and its summary statistics.
I am missing something with my code, but unable to guess.
ui<-dashboardPage(
dashboardHeader(title = "Claim Model"),
dashboardSidebar(
sidebarMenu(id="tabs",
menuItem("Data", tabName = "data", icon = icon("table"),startExpanded = TRUE,
menuSubItem("Load", tabName = "data1")
),
menuItem("Visualisation",icon=icon("bar-chart-o"), tabName = "vis"),
menuItem("Result", icon=icon("cog"), tabName = "result")
)
),
dashboardBody(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
tabItems(
tabItem(tabName = "data1",
fluidPage(
fluidRow(
fileInput("file1","Choose CSV File",
accept = c("text/csv",
"text/comma-seperated-values, text/plain",
".csv")
),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons("sep","Separator",
choices=c(Comma=",",
semicolon=";",
Tab="\t"),
selected = ";")
),
mainPanel(
tableOutput("contents")
)
)
)
)
)
)
Server Code.
server <- shinyServer(function(input,output){
output$contents <- renderTable({
req(input$file1)
df <- read.csv(input$file1$datapath,
header=input$header,
sep=input$sep)
})
})
Currently i dont have the code for displaying the statistics from data frame. any lead on how to start would be helpful
Here is an example: Inside dashboardBody(), you need a second (and third) tabItem() to "fill" the menuItem(tabName = "vis") and menuItem(tabName = "result"). And in the server, you need code to generate plots or tables or whatever you want to display. Furthermore, note how I assigned the output of read.csv() to a function (called DATA() here) so that it can be used at different places inside the server.
UI:
ui <- dashboardPage(
dashboardHeader(title = "Claim Model"),
dashboardSidebar(
sidebarMenu(id="tabs",
menuItem("Data", tabName = "data", icon = icon("table"),startExpanded = TRUE,
menuSubItem("Load", tabName = "data1")
),
menuItem("Visualisation",icon=icon("bar-chart-o"), tabName = "vis"),
menuItem("Result", icon=icon("cog"), tabName = "result")
)
),
dashboardBody(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
tabItems(
tabItem(tabName = "data1",
fluidPage(
fluidRow(
fileInput("file1","Choose CSV File",
accept = c("text/csv",
"text/comma-seperated-values, text/plain",
".csv")
),
tags$hr(),
checkboxInput("header", "Header", TRUE),
radioButtons("sep","Separator",
choices=c(Comma=",",
semicolon=";",
Tab="\t"),
selected = ";")
),
mainPanel(
tableOutput("contents")
)
)
),
tabItem(tabName = "vis", h2("Two Plots"),
fluidRow(
box(
title = "Plot 1", solidHeader = TRUE, collapsible = TRUE,
plotOutput("hist1")
),
box(
title = "Plot 2", solidHeader = TRUE, collapsible = TRUE,
plotOutput("hist2")
)
)
)
)
)
)
server:
server <- function(input, output) {
DATA <- reactive({
req(input$file1)
df <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep)
return(df)
})
output$contents <- renderTable(DATA())
output$hist1 <- renderPlot({
tmp1 <- sample(which(apply(DATA(), 2, is.numeric)), 1)
hist(DATA()[, tmp1], breaks = 10, xlab = names(DATA())[tmp1], main = "")
})
output$hist2 <- renderPlot({
tmp1 <- sample(which(apply(DATA(), 2, is.numeric)), 1)
hist(DATA()[, tmp1], breaks = 20, xlab = names(DATA())[tmp1], main = "")
})
}
run:
library(shiny)
library(shinydashboard)
shinyApp(ui, server)

Resources