My ui.R
library(shiny)
library(stats)
library(caret)
shinyUI(fluidPage(
titlePanel("Predicting Resources for Vessel"),
title = "Resource Prediction",
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose a Import BAPLE(.CSV) file to upload:",
accept = c("text/csv", "text/comma-separated-values, text/plain", ".csv")),
fileInput("file2", "Choose a Export BAPLE(.csv) file to upload:",
accept = c("text/csv", "text/comma-separated-values, text/plain", ".csv")),
fileInput("file3", "Choose a Import/Export containers yard location(.CSV) file to upload:",
accept = c("text/csv", "text/comma-separated-values, text/plain", ".csv")),
tags$hr(),
h4("Manual Input:"),
numericInput("Restow_40","Total Restows for 40ft Container:", 0, min = 0, max = 999999, step = 1),
textInput("Berth","Vessel Berth Location (CB3/CB4)"),
actionButton("submit", "Submit")
),
mainPanel(
tabsetPanel(
tabPanel("Raw Data", dataTableOutput("data")),
tabPanel("Output", verbatimTextOutput("pred_output"))
)
)
)
))
This is my server.r file
library(shiny)
library(stats)
#library(caret)
library(mlr)
library(data.table)
shinyServer(function(input, output) {
######################### Reading the required files ###################################
import_baple <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
read.csv(inFile$datapath)
})
export_baple <- reactive({
inFile <- input$file2
if (is.null(inFile)) return(NULL)
read.csv(inFile$datapath)
})
import_export_yard <- reactive({
inFile <- input$file3
if (is.null(inFile)) return(NULL)
read.csv(inFile$datapath)
})
output$data <- renderDataTable({
import_baple()
})
output$data <- renderDataTable({
export_baple()
})
output$data <- renderDataTable({
import_export_yard()
})
})
I want all the three files when uploaded to be displayed in Raw Data tab. When I upload first two files no content is displayed in the Raw Tab, but when I upload the third file content is displayed in the tab. I am not getting where I am doing it wrong.
Each input/output element needs a unique identifier, otherwise Shiny doesn't know which of the elements with the given identifier to use. So where you have:
tabPanel("Raw Data", dataTableOutput("data"))
In your UI and:
output$data <- renderDataTable({
import_baple()
})
output$data <- renderDataTable({
export_baple()
})
output$data <- renderDataTable({
import_export_yard()
})
In your server, what you actually need is more like:
# UI
tabPanel("Raw Data",
dataTableOutput("import_baple_data"),
dataTableOutput("explort_baple_data"),
dataTableOutput("import_export_data")
)
# Server
output$import_baple_data <- renderDataTable({
import_baple()
})
output$export_baple_data <- renderDataTable({
export_baple()
})
output$import_export_data <- renderDataTable({
import_export_yard()
})
Related
I'm trying to make a simple Shiny dashboard using the iris dataset in R.
What I accomplished so far: The current dashboard has two dropdowns. One that filters the Species column and one for the subspecies column that's dependent on the first dropdown. These two dropdowns work.
What's not working: Based on the two dropdowns, I'd like to see a datatable which should be a filtered dataset.
I think I'm using a wrong name space ?
Any advice would be of great help!
library(shiny)
library(DT)
library(dplyr)
## global.R
# Create sub_species column
iris2 <- iris %>%
mutate(
subspecies = case_when(
startsWith(as.character(Species), "setosa") ~ rep(c("setosa1", "setosa2"), length.out = n()),
startsWith(as.character(Species), "versicolor") ~ rep(c("versicolor1", "versicolor2"), length.out = n()),
startsWith(as.character(Species), "virginica") ~ rep(c("virginica1", "virginica2"), length.out = n())
)
)
## ui.R
fluidPage(
sidebarLayout(
sidebarPanel(
dropdownsUI("dropdowns")
),
mainPanel(
DT::dataTableOutput("table1")
)
)
)
## server.R
function(input, output, session) {
subspeciesServer("dropdowns")
data1 <- filteredDataServer("table1")
output$table1 <- DT::renderDataTable({
data1()
})
}
## modules.R
# UI logic
dropdownsUI <- function(id) {
ns <- NS(id)
# All input IDs in the function body must be wrapped with ns()
tagList(
selectInput(ns("speciesDropdown"), label = "Species:", choices = c("setosa", "versicolor", "virginica")),
uiOutput(ns("subspeciesDropdown")),
DT::dataTableOutput(ns("datatable"))
)
}
# Sub Species Dropdown logic
subspeciesServer <- function(id) {
moduleServer(id, function(input, output, session) {
dependent_subspecies <- reactive({
iris2 %>%
filter(Species == req(input$speciesDropdown)) %>%
pull(subspecies) %>%
unique()
})
output$subspeciesDropdown <- renderUI({
selectInput("vars_subspecies", "Sub Species:", choices = dependent_subspecies())
})
}
)
}
# Filtered data logic
filteredDataServer <- function(id) {
moduleServer(id, function(input, output, session) {
df <- reactive({
req(input$speciesDropdown, input$subspeciesDropdown)
iris2 %>%
# may be this what's causing the error ?
filter(Species %in% input$speciesDropdown & subspecies %in% input$vars_subspecies)
})
return(df)
}
)
}
Apart from namespace issue, you had a few other issues. You need to pass the reactive variables between modules. They are not available globally. Try this
library(shiny)
library(DT)
library(dplyr)
## global.R
# Create sub_species column
iris2 <- iris %>%
dplyr::mutate(
subspecies = case_when(
startsWith(as.character(Species), "setosa") ~ rep(c("setosa1", "setosa2"), length.out = n()),
startsWith(as.character(Species), "versicolor") ~ rep(c("versicolor1", "versicolor2"), length.out = n()),
startsWith(as.character(Species), "virginica") ~ rep(c("virginica1", "virginica2"), length.out = n())
)
)
## modules.R
# UI logic
dropdownsUI <- function(id) {
ns <- NS(id)
# All input IDs in the function body must be wrapped with ns()
tagList(
selectInput(ns("speciesDropdown"), label = "Species:", choices = c("setosa", "versicolor", "virginica")),
uiOutput(ns("subspeciesDropdown"))
#,DT::dataTableOutput(ns("datatable"))
)
}
# Sub Species Dropdown logic
subspeciesServer <- function(id) {
moduleServer(id, function(input, output, session) {
ns <- session$ns
rv <- reactiveValues()
dependent_subspecies <- reactive({
iris2 %>%
filter(Species == req(input$speciesDropdown)) %>%
pull(subspecies) %>%
unique()
})
output$subspeciesDropdown <- renderUI({
req(dependent_subspecies())
selectInput(ns("vars_subspecies"), "Sub Species:", choices = dependent_subspecies())
})
observe({
rv$var1 <- input$speciesDropdown
rv$var2 <- input$vars_subspecies
})
return(rv)
}
)
}
# Filtered data logic
filteredDataServer <- function(id,sp,subsp,mydf) {
moduleServer(id, function(input, output, session) {
df <- reactive({
mydf %>% dplyr::filter(subspecies %in% subsp())
})
return(df)
}
)
}
## ui.R
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
dropdownsUI("dropdowns")
),
mainPanel(
DT::dataTableOutput("table1")
)
)
)
## server.R
server <- function(input, output, session) {
myvars <- subspeciesServer("dropdowns")
data1 <- filteredDataServer("table1", reactive(myvars$var1), reactive(myvars$var2),iris2)
output$table1 <- DT::renderDataTable({
datatable(req(data1()))
})
}
shinyApp(ui = ui, server = server)
I'm building a shiny app that would display in dygraphs a basic dataset and then offer an option to add new time series upon selecting the checkbox input. However, as I coded it now, I'm 'stuck' at the original dataset and unable to add/remove new content. Any hints how to solve this are very welcome, thanks.
library(shinydashboard)
library(dygraphs)
library(dplyr)
ui <-dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
useShinyjs(),
checkboxGroupInput(inputId = 'options',
label = 'Choose your plot(s)',
choices = list("mdeaths" = 1,
"ldeaths" = 2)
),
uiOutput("Ui1")
)
)
server <- function(input, output, session) {
output$Ui1 <- renderUI({
output$plot1 <- renderDygraph({
final_ts <- ldeaths
p <- dygraph(final_ts, main = 'Main plot') %>%
dygraphs::dyRangeSelector()
if(1 %in% input$options) {
final_ts <- cbind(final_ts, mdeaths)
p <- p %>%
dySeries('mdeaths', 'Male Deaths')
} else if(2 %in% input$options) {
final_ts <- cbind(final_ts, fdeaths)
p <- p %>%
dySeries('fdeaths', 'Female Deaths')
}
p
})
dygraphOutput('plot1')
})
}
shinyApp(ui, server)
I'd suggest to dynamically filter the data based on the user selection instead of dynamically adding/removing traces from the plot:
library(shinydashboard)
library(shinyjs)
library(dygraphs)
library(dplyr)
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
useShinyjs(),
selectizeInput(
inputId = "options",
label = "Choose your trace(s)",
choices = colnames(lungDeaths),
selected = colnames(lungDeaths)[1],
multiple = TRUE,
options = list('plugins' = list('remove_button'))
),
uiOutput("Ui1")
)
)
server <- function(input, output, session) {
output$Ui1 <- renderUI({
filteredLungDeaths <- reactive({
lungDeaths[, input$options]
})
output$plot1 <- renderDygraph({
p <- dygraph(filteredLungDeaths(), main = 'Main plot') %>%
dygraphs::dyRangeSelector()
if('mdeaths' %in% colnames(filteredLungDeaths())){
p <- dySeries(p, 'mdeaths', 'Male Deaths')
}
if('fdeaths' %in% colnames(filteredLungDeaths())){
p <- dySeries(p, 'fdeaths', 'Female Deaths')
}
p
})
dygraphOutput('plot1')
})
}
shinyApp(ui, server)
I developed a Shiny application to include couple of plots and data under different tabs.Tabs are created dynamically using another parameter.But each time i have to subset the data to prepare the plots. Say using 'mpg' subsetdata i plotted 2 different types of graphs in 'mpg' tab and i don't want to subset data every time(currently i sub set every time) when i draw the plot.For all calculations in one tab, i would like to subset the data only once.Appreciate some help
write.csv(mtcars,'mtcars.csv')
write.csv(mtcars,'mtcars.csv')
library(shiny)
library(plyr)
library(dplyr)
library(DT)
library(data.table)
ui <- pageWithSidebar(
headerPanel = headerPanel('data'),
sidebarPanel = sidebarPanel(fileInput(
'mtcars', h4('Uplaodmtcardata in csv format')
),
uiOutput('tabnamesui')),
mainPanel(uiOutput("tabsets"))
)
server <- function(input, output, session) {
mtcarsFile <- reactive({
input$mtcars
})
xxmtcars <-
reactive({
read.table(
file = mtcarsFile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(xxmtcars())
})
output$tabnamesui <- renderUI({
req(mtcarsFile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
multiple = T
# selected = SalesGlobalDataFilter1Val()
)
})
tabnamesinput <- reactive({
input$tabnamesui
})
output$tabsets <- renderUI({
req(mtcarsFile())
tabs <-
reactive({
lapply(tabnamesinput(), function(x)
tabPanel(title = basename(x)
,fluidRow(splitLayout(cellWidths = c("50%", "50%"),
plotOutput(paste0('plot1',x)),
plotOutput(paste0('plot2',x)
))),fluidRow(splitLayout(cellWidths =
c("50%", "50%"),
plotOutput(paste0('plot3',x)),
plotOutput(paste0('plot4',x)
))),
dataTableOutput(paste0('table',x))))
})
do.call(tabsetPanel, c(tabs()))
})
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('table',x)]] <-
renderDataTable({as.data.table((select(xxmtcars(),x)))#CODE REPEATED
})}))
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot1',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE REPEATED
})
})
)
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot2',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE #REPEATED
})
})
)
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot3',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE REPEATED
})
})
)
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('plot4',x)]] <-
renderPlot({as.data.table((select(xxmtcars(),x)))%>%plot()#CODE REPEATED
})
})
)
}
runApp(list(ui = ui, server = server))
You can save your sub data into a reactive object and call it when you need.
library(shiny)
library(plyr)
library(dplyr)
library(DT)
library(data.table)
ui <- pageWithSidebar(
headerPanel = headerPanel('data'),
sidebarPanel = sidebarPanel(fileInput(
'mtcars', h4('Uplaodmtcardata in csv format')
),
uiOutput('tabnamesui')),
mainPanel(uiOutput("tabsets"))
)
server <- function(input, output, session) {
mtcarsFile <- reactive({
input$mtcars
})
xxmtcars <-
reactive({
read.table(
file = mtcarsFile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(xxmtcars())
})
output$tabnamesui <- renderUI({
req(mtcarsFile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
multiple = T
# selected = SalesGlobalDataFilter1Val()
)
})
tabnamesinput <- reactive({
input$tabnamesui
})
output$tabsets <- renderUI({
req(mtcarsFile())
tabs <-
reactive({
lapply(tabnamesinput(), function(x)
tabPanel(title = basename(x)
,fluidRow(splitLayout(cellWidths = c("50%", "50%"),
plotOutput(paste0('plot1',x)),
plotOutput(paste0('plot2',x)
))),fluidRow(splitLayout(cellWidths =
c("50%", "50%"),
plotOutput(paste0('plot3',x)),
plotOutput(paste0('plot4',x)
))),
dataTableOutput(paste0('table',x))))
})
do.call(tabsetPanel, c(tabs()))
})
# Save your sub data here
subsetdata<-reactive({
list_of_subdata<-lapply(tabnamesinput(), function(x) {
as.data.table((select(xxmtcars(),x)))
})
names(list_of_subdata)<-tabnamesinput()
return(list_of_subdata)
})
observe(
lapply(tabnamesinput(), function(x) {
output[[paste0('table',x)]] <-
renderDataTable({
subsetdata()[[x]]
})}))
observe(
lapply(tabnamesinput(), function(x) {
for(i in paste0("plot",1:4)){
output[[paste0(i,x)]] <-
renderPlot({subsetdata()[[x]]%>%plot()#CODE REPEATED
})
}
})
)
}
runApp(list(ui = ui, server = server))
I am building an application in shiny R where in required tabs can be selected by the users and data relevant to those tabs will be displayed under it.
For example, in below sample application, mtcars data in .csv will be accepted as input parameter.User can select required column names in tabs field.Those colmns will be created as tabs.
Now, I want to show data pertaining to that column from .csv in the appropriate tab.Say, data from the column 'mpg' will be shown under 'mpg' tab.
But i am stuck here.Appreciate someone could tell me a way to display data from relevant column under appropriate tab ,dynamically.
Sample codes used is shown below:
write.csv(mtcars,'mtcars.csv')
#
library(shiny)
library(plyr)
library(dplyr)
ui <- pageWithSidebar(
headerPanel = headerPanel('data'),
sidebarPanel = sidebarPanel(fileInput(
'mtcars', h4('Uplaodmtcardata in csv format')
),
uiOutput('tabnamesui')),
mainPanel(uiOutput("tabsets"))
)
server <- function(input, output, session) {
mtcarsFile <- reactive({input$mtcars})
xxmtcars <-
reactive({
read.table(
file = mtcarsFile()$datapath,
sep = ',',
header = T,
stringsAsFactors = T
)
})
tabsnames <- reactive({
names(xxmtcars())
})
output$tabnamesui <- renderUI({
req(mtcarsFile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
multiple = T
)
})
tabnamesinput <- reactive({
input$tabnamesui
})
output$tabsets <- renderUI({
req(mtcarsFile())
tabs <-
reactive({
lapply(tabnamesinput(), function(x)
tabPanel(title = basename(x), dataTableOutput(x)))
})
do.call(tabsetPanel, c(tabs()))
})
output[['mpg']] <-
renderDataTable(as.data.frame(select(xxmtcars(), mpg)))#HOW TO AVOID THIS HARD CODING..?BASED ON THE TAB NAME DATA FROM RELEVANT COLUMN IN THE CSV TO BE RETURNED.
}
runApp(list(ui = ui, server = server))
#
Try this
library(shiny)
library(plyr)
library(dplyr)
library(rlang)
library(DT)
ui <- pageWithSidebar(
headerPanel = headerPanel('data'),
sidebarPanel = sidebarPanel(fileInput(
'mtcars', h4('Uplaodmtcardata in csv format')
),
uiOutput('tabnamesui')),
mainPanel(uiOutput("tabsets"))
)
server <- function(input, output, session) {
mtcarsFile <- reactive({input$mtcars})
xxmtcars <-
reactive({
read.table(
file = mtcarsFile()$datapath,
sep = ',',
header = T,
stringsAsFactors = FALSE
)
})
tabsnames <- reactive({
names(xxmtcars())
})
output$tabnamesui <- renderUI({
req(mtcarsFile())
selectInput(
'tabnamesui',
h5('Tab names'),
choices = as.list(tabsnames()),
multiple = T
)
})
tabnamesinput <- reactive({
input$tabnamesui
})
output$tabsets <- renderUI({
req(mtcarsFile())
tabs <-
reactive({
lapply(tabnamesinput(), function(x)
tabPanel(title = basename(x), dataTableOutput(x)))
})
do.call(tabsetPanel, c(tabs()))
})
observe(
lapply(tabnamesinput(), function(x) {
output[[x]] <- DT::renderDataTable({
t<-as.data.frame(dplyr::select(xxmtcars(), !! sym(x)) )
print(t)
datatable(t)
})
})
)
}
runApp(list(ui = ui, server = server))
I am trying to develop a shiny app where there are data inputs on multiple tabs. The content under each tab works fine on its own however when i attempt to combine them into one app I continue to get this error. Error in match.arg(position) : 'arg' must be NULL or a character vector. My code is as follows:
library(shiny)
library(shinydashboard)
library(ggvis)
sidebar <- dashboardSidebar(
hr(),
sidebarMenu(id="tabs",
menuItem("Import Data", tabName = "Import", icon=icon("list-alt")),
menuItem("Bivariate Regression", tabName="Bivariate Regression", icon=icon("line-chart")),
menuItem("Contingency", tabName = "Contingency", icon = icon("table"))
))
body <- dashboardBody(
tabItems(
tabItem(tabName= "Import",
sidebarLayout(
sidebarPanel(
fileInput("file","Upload the file"),
tags$hr(),
h5(helpText("Select the table parameters below")),
checkboxInput(inputId = 'header', label= 'Header', value= TRUE),
checkboxInput(inputId = "stringsAsFactors", "stringsAsFactors", FALSE),
br(),
radioButtons(inputId = 'sep', label = 'Seperator', choices = c(Comma=',', Semicolon=';', Tab='\t', Space= ' '), selected= ',')
),
mainPanel(
uiOutput("tb")
)
)),
tabItem(tabName= "Bivariate Regression",
sidebarLayout(
div(),
sidebarPanel(
fileInput('datfile', ''),
selectInput('x', 'x:' ,'x'),
selectInput('y', 'y:', 'y'),
uiOutput("plot_ui")
),
mainPanel(
titlePanel("Plot Output"),
ggvisOutput("plot")
)
))
))
dashboardPage(
dashboardHeader(title = "COBE Dashboard"),
sidebar,
body)
and server
library(shiny)
library(dplyr)
library(ggvis)
shinyServer(function(input, output){
#read the data and give import prefrences
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep= input$sep, header= input$header, stringsAsFactors= input$stringsAsFactors)
})
# display summary of table output
output$filledf <-renderTable({
if(is.null(data())){return ()}
input$file
})
output$sum <- renderTable({
if(is.null(data())){return ()}
summary(data())
})
output$table <- renderTable({
if(is.null(data())){return ()}
data()
})
#generate tabsets when the file is loaded.
output$tb <- renderUI({
if(is.null(data()))
h2("App powered by", tags$img(src='Blue.png', height= 100, width=250))
else
tabsetPanel(tabPanel("About file", tableOutput("filledf")), tabPanel("Data", tableOutput("table")), tabPanel("Summary", tableOutput("sum")))
})
########## Data import end #########
########## Bivariate regression begin ###########
#load the data when the user inputs a file
theData <- reactive({
infile <- input$datfile
if(is.null(infile))
return(NULL)
d <- read.csv(infile$datapath, header = T)
d
})
# dynamic variable names
observe({
data<-theData()
updateSelectInput(session, 'x', choices = names(data))
updateSelectInput(session, 'y', choices = names(data))
}) # end observe
#gets the y variable name, will be used to change the plot legends
yVarName<-reactive({
input$y
})
#gets the x variable name, will be used to change the plot legends
xVarName<-reactive({
input$x
})
#make the filteredData frame
filteredData<-reactive({
data<-isolate(theData())
#if there is no input, make a dummy dataframe
if(input$x=="x" && input$y=="y"){
if(is.null(data)){
data<-data.frame(x=0,y=0)
}
}else{
data<-data[,c(input$x,input$y)]
names(data)<-c("x","y")
}
data
})
#plot the ggvis plot in a reactive block so that it changes with filteredData
vis<-reactive({
plotData<-filteredData()
plotData %>%
ggvis(~x, ~y) %>%
layer_points() %>%
add_axis("y", title = yVarName()) %>%
add_axis("x", title = xVarName()) %>%
add_tooltip(function(df) format(sqrt(df$x),digits=2))
})
vis%>%bind_shiny("plot", "plot_ui")
##### add contingency table ########
# display contingcy table output
output$foo <- renderTable({
if(is.null(data())){return ()}
as.data.frame.matrix(table((data())))
})
})
There is an extra div() element in the second tabItem in tabItems in ui.R. Either provide an argument you implied to or remove that div() element. Also, I have added session argument to the shinyServer() function in server.R. After these changes app is running without any errors.
EDIT :
You forgot to add one more tabItem for Contingency in tabItems() function. Also, it is always better to differentiate between tabName and the title for that tab. And there should be no spaces in the tab name as per my experience, that is the reason why Bivariate Regression tab was not working before. It should work fine now.
Updated code:
ui.R
library(shiny)
library(shinydashboard)
library(ggvis)
sidebar <- dashboardSidebar(
br(),
sidebarMenu(id="tabs",
menuItem("Import Data", tabName = "import", icon=icon("list-alt")),
menuItem("Bivariate Regression", tabName="bivariate_regression", icon=icon("line-chart")),
menuItem("Contingency", tabName = "contingency", icon = icon("table"))
))
body <- dashboardBody(
tabItems(
tabItem(tabName= "import",
sidebarLayout(
sidebarPanel(
fileInput("file","Upload the file"),
tags$hr(),
h5(helpText("Select the table parameters below")),
checkboxInput(inputId = 'header', label= 'Header', value= TRUE),
checkboxInput(inputId = "stringsAsFactors", "stringsAsFactors", FALSE),
br(),
radioButtons(inputId = 'sep', label = 'Seperator', choices = c(Comma=',', Semicolon=';', Tab='\t', Space= ' '), selected= ',')
),
mainPanel(
uiOutput("tb")
)
)),
tabItem(tabName= "bivariate_regression",
sidebarLayout(
#div(),
sidebarPanel(
fileInput('datfile', ''),
selectInput('x', 'x:' ,'x'),
selectInput('y', 'y:', 'y'),
uiOutput("plot_ui")
),
mainPanel(
titlePanel("Plot Output"),
ggvisOutput("plot")
)
)),
tabItem(tabName="contingency", h2("Contigency Tab content"))
))
dashboardPage(
dashboardHeader(title = "COBE Dashboard"),
sidebar,
body)
server.R
library(shiny)
library(dplyr)
library(ggvis)
shinyServer(function(input, output,session){
#read the data and give import prefrences
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep= input$sep, header= input$header, stringsAsFactors= input$stringsAsFactors)
})
# display summary of table output
output$filledf <-renderTable({
if(is.null(data())){return ()}
input$file
})
output$sum <- renderTable({
if(is.null(data())){return ()}
summary(data())
})
output$table <- renderTable({
if(is.null(data())){return ()}
data()
})
#generate tabsets when the file is loaded.
output$tb <- renderUI({
if(is.null(data()))
h2("App powered by", tags$img(src='Blue.png', height= 100, width=250))
else
tabsetPanel(tabPanel("About file", tableOutput("filledf")), tabPanel("Data", tableOutput("table")), tabPanel("Summary", tableOutput("sum")))
})
########## Data import end #########
########## Bivariate regression begin ###########
#load the data when the user inputs a file
theData <- reactive({
infile <- input$datfile
if(is.null(infile))
return(NULL)
d <- read.csv(infile$datapath, header = T)
d
})
# dynamic variable names
observe({
data<-theData()
updateSelectInput(session, 'x', choices = names(data))
updateSelectInput(session, 'y', choices = names(data))
}) # end observe
#gets the y variable name, will be used to change the plot legends
yVarName<-reactive({
input$y
})
#gets the x variable name, will be used to change the plot legends
xVarName<-reactive({
input$x
})
#make the filteredData frame
filteredData<-reactive({
data<-isolate(theData())
#if there is no input, make a dummy dataframe
if(input$x=="x" && input$y=="y"){
if(is.null(data)){
data<-data.frame(x=0,y=0)
}
}else{
data<-data[,c(input$x,input$y)]
names(data)<-c("x","y")
}
data
})
#plot the ggvis plot in a reactive block so that it changes with filteredData
vis<-reactive({
plotData<-filteredData()
plotData %>%
ggvis(~x, ~y) %>%
layer_points() %>%
add_axis("y", title = yVarName()) %>%
add_axis("x", title = xVarName()) %>%
add_tooltip(function(df) format(sqrt(df$x),digits=2))
})
vis%>%bind_shiny("plot", "plot_ui")
##### add contingency table ########
# display contingcy table output
output$foo <- renderTable({
if(is.null(data())){return ()}
as.data.frame.matrix(table((data())))
})
})