I tried to read dataframe rows from one column to feel a list in a SelectInput objet in a UI.R Shiny
I have a problem with global or local ref between the UI and Server and I don't know if the format is right to import items in the selectInput List
Here my DF Ref_comp with just one column (STEP_NAME):
! STEP_NAME !
-----------------
L1_2_3_LR
C46-C77-OTHERS
R4
R10
C56
Q4
L4
Here my UI.R
shinyUI(pageWithSidebar(
headerPanel("My header Text"),
sidebarPanel(
radioButtons("test", "Select a DataBase",
c("test1"="test1",
"test2"="test2")),
textInput("card", "Enter the code card", "CARD.EX"),
textInput("comp", "Enter the ref comp", "R3"),
######## Here what I tried to do ########
selectInput("comp_sel","Component", choices=
as.character(unique(unlist(Ref_comp$STEP_NAME)))),
##########################################
downloadButton("plot_export", "Save PDF")
),
mainPanel(
#h4("Text2"),
library(plotly),
plotlyOutput("plot"))
))
Here my Server.R
shinyServer(function(input,output){
output$plot <- renderPlotly({
con <- odbcConnect(con, uid="xxx")
##### Here the SQL Query to have my items ######################
sql_ref = paste("select DISTINCT ...") # My SQL query on distant server
###### Output in DF Ref_comp ##############
Ref_comp <- sqlQuery(db, paste (sql_ref))
##########################################
odbcClose(data_testeur)
#### An other SQL Query for the graph #######
graph <- ggplot(...
ggplotly(graph) # Print graph
}
)
})
Thank you for your help
Your problem is that you the data_frame Ref_comp is generated in server.r when this is the case we have to generate the selectInput dynamic with a renderUI and uiOutput() like this:
shinyUI(pageWithSidebar(
headerPanel("My header Text"),
sidebarPanel(
radioButtons("test", "Select a DataBase",
c("test1"="test1",
"test2"="test2")),
textInput("card", "Enter the code card", "CARD.EX"),
textInput("comp", "Enter the ref comp", "R3"),
######## Here what I tried to do ########
uiOutput("selectComp"),
##########################################
downloadButton("plot_export", "Save PDF")
),
mainPanel(
#h4("Text2"),
library(plotly),
plotlyOutput("plot"))
))
and server
shinyServer(function(input,output){
refDataFrame <- reactive({
con <- odbcConnect(con, uid="xxx")
##### Here the SQL Query to have my items ######################
sql_ref = paste("select DISTINCT ...") # My SQL query on distant server
###### Output in DF Ref_comp ##############
Ref_comp <- sqlQuery(db, sql_ref)
odbcClose(data_testeur)
Ref_comp
})
output$selectComp <- renderUI(
selectInput("comp_sel","Component", choices=
as.character(unique(unlist(refDataFrame()[["STEP_NAME"]]))))
)
output$plot <- renderPlotly({
Ref_comp <- refDataFrame()
#### An other SQL Query for the graph #######
graph <- ggplot(...)
ggplotly(graph) # Print graph
}
)
})
Since we now need the result of the database query in two places have put it in a separate reactive function
Related
My goal is that user uploads an Excel file. Then, the user selects which sheets wants to be summarised, after the selection has been updated. I have managed to update selectInput with the name of the sheets but I have not been able to find\understand how to summarise based on what the sheet selected by the user. Thanks for any help.
library(shiny)
library(shinythemes)
library(data.table)
library(ggplot2)
library(dplyr)
library(readxl)
not_sel <- "Not Selected"
# Define UI for application that draws a histogram
ui <- fluidPage('MAIN TITLE',
theme = shinytheme('flatly'),
tabsetPanel(
sidebarLayout(
sidebarPanel(
fileInput('files','Import File', accept = c('.csv','.xlsx'),
multiple = F),
actionButton('boton1', 'Load', icon = icon('table')),
br(),
selectInput("indices", "Select SHEET:", choices = c(not_sel))
),
mainPanel(
tabsetPanel(
tabPanel('Data',
tableOutput('tabla'),
tableOutput('cabeza')),
tabPanel('Stats',
# selectInput('var01', 'Variable to summarise', choices = c(not_sel)),
tableOutput('stats')),
)
)
)
)
)
##############
server <- function(input, output, session) {
options(shiny.maxRequestSize=10*1024^2)
df <- eventReactive(input$boton1, {
req(input$files)
if(is.null(input$files))return(NULL)
# else{
read_excel(input$files$datapath)
# }
})
# Sheets of file uploaded
sheets_name <- reactive({
if (!is.null(input$files)) {
return(excel_sheets(path = input$files$datapath))
} else {
return(NULL)
}
})
# Update inputSelector with sheet names
observeEvent(df(),{
choices <- c(sheets_name())
updateSelectInput(inputId = "indices", choices = choices)
})
# DATA Tab
## This will show the name of the file
output$tabla <- renderTable({
input$files$name
})
## This Shows the head() but it is only showing the first sheet
output$cabeza <- renderTable({
tabla <- as_tibble(bind_cols(Date = format(as.Date(df()$Date),"%Y-%m-%d"),
Close.Price = df()$Close))
head(tabla)
})
# HERE is where I do not know how to calculate based on selection
# Table for STATS
output$stats <- renderTable({
datos <- df()
Value <- c(round(mean(datos$Close,na.rm = T),2)
)
Statistic <- c("Mean")
data.table(Statistic, Value)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I want to assume that by knowing how to calculate mean based on the sheet selected, I. can replicate the code for the top rows (head()) shown in the Data Panel.
If I missed a similar question asked, I would appreciate any link and I will try the solution proposed first.
As I cannot share the file, this is how the file would look:
After working with this answer I made my app work. If there is a 'cleaner'/'better' answer, I will be happy to read.
Following the recommendation in the linked answer my server ended up like this:
ui <-fluidPage{
#My UI stayed the same with the exception of adding
uiOutput("dropdownUI") #Whererever I needed to appear
}
server <- function(input, output, session) {
...ANSWER FROM THE LINK...
## STATS Tab
output$stats <- renderTable({
Values <- c(round(mean(Dat()[,2],na.rm = T),2)
)
Statistics <- c("Mean")
data.table(Statistics, Values)
})
}
I'm having an issue which I thought would have been very simple to solve, but I cannot figure it out.
I simply want to pass an uploaded csv file to a custom function in Shiny and output the result which is a ggplot graph. Here is my code for doing so
# Getting the file names
rdsfiles <- list.files(pattern = "\\.Rds$")
# --- Front End ---
ui <- shinyUI(fluidPage(theme = shinytheme("cerulean"), pageWithSidebar(
# Title
headerPanel("Title"),
# Sidebar to select a dataset
sidebarPanel(
selectInput("obj", "Choose a dataset:",
choices = rdsfiles),
fileInput("tissue_csv",
"Load tissue positions .csv file",
accept = c("text/csv", "text/comma-separated-values,text/plain",".csv")
),
textInput("feature", label = "Gene"),
),
# Different analyses available
mainPanel(
tabsetPanel(
tabPanel('UMAP', plotOutput("umap")),
tabPanel('Tissue', plotOutput("tissue")),
tabPanel('Gene Expression', plotOutput("genex")),
))
)))
# --- Back end ---
server <- shinyServer(function(input, output) {
# Return the requested datasets
datasetInput <- reactive({
df <- readRDS(input$obj, input$obj)
return(df)
})
tissueInput <- reactive({
inFile <- req(input$tissue_csv)
read.csv(inFile$datapath)
})
### HERE IS WHERE THE ERROR LIES ###
output$tissue <- renderPlot({
obj <- datasetInput()
tiss <- tissueInput()
custom_function(obj, tiss)
})
# Retrieve the UMAP projection
output$umap <- renderPlot({
obj <- datasetInput()
DimPlot(obj, reduction = "umap")
})
})
shinyApp(ui, server)
Whenever I use the app and upload my .csv file, it always gives me an error message that says 'file' must be a character string or connection. Why is this? Any suggestions?
I'm trying to create a shiny dashboard that allows the user to select a csv file. The file contains only two columns that are order number and dateCreated. I want the user to be able to in addition, select the date range that they desire and get a summary count statistic.
So far my code is as follows:
library(shiny)
library(plotly)
library(colourpicker)
library(ggplot2)
ui <- fluidPage(
titlePanel("Case Referrals"),
sidebarLayout(
sidebarPanel(
fileInput("file", "Select a file"),
sliderInput("period", "Time period observed:",
min(data()[, c('dateCreated')]), max(data()[, c('dateCreated')]),
value = c(min(data[, c('dateCreated')]),max(data()[, c('dateCreated')])))
),
mainPanel(
DT::dataTableOutput("table")
)
)
)
# Define the server logic
server <- function(input, output) {
# file input
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
})
# summarizing data into counts
data <- input_file()
data <- subset(data, dateCreated >= input$period[1] & dateCreated <= input$period[2])
output$table <- DT::renderDataTable({
data
})
}
shinyApp(ui = ui, server = server)
I get an error message saying:
Error in data()[, c("dateCreated")] : incorrect number of dimensions
Can anyone help me understand what the problem might be and/or provide a better framework for doing this? And to be clear in the csv file, the createDate variable is broken down into individual days for when the order was placed.
Thank you!
I added comments to the faulty steps.
library(shiny)
ui <- fluidPage(
titlePanel("Case Referrals"),
sidebarLayout(
sidebarPanel(
fileInput("file", "Select a file"),
# you cannot call data() in your ui.
# You would have to wrap this in renderUI inside of your server and use
# uiOutput here in the ui
sliderInput("period", "Time period observed:", min = 1, max = 10, value = 5)
),
mainPanel(
DT::dataTableOutput("table")
)
)
)
# Define the server logic
server <- function(input, output) {
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
# actually read the file
read.csv(file = input$file$datapath)
})
output$table <- DT::renderDataTable({
# render only if there is data available
req(input_file())
# reactives are only callable inside an reactive context like render
data <- input_file()
data <- subset(data, dateCreated >= input$period[1] & dateCreated <= input$period[2])
data
})
}
shinyApp(ui = ui, server = server)
I am trying to render DataTable output to Shiny. Please find below explanation of my use case:
Connected to my database and got table data to df variable.
sent selected input from select input text box to server script.
Server script should take this input and get the data.
ui.R
library(shiny)
library(RODBC)
library(DBI)
# Establishing connection to ORE environment
dbconnect <- odbcConnect("orecloud", uid="XXXX", pwd="XXXXX", believeNRows=FALSE)
# Preparing data frames to get the data and show in select input pick list
df <- data.frame()
df <- sqlQuery(dbconnect,"SELECT distinct cpan FROM TABLE ")
shinyUI(fluidPage(
headerPanel("ORE XXX Summary"),
sidebarLayout(
sidebarPanel(
helpText("Please select Patient Details.."),
selectInput("CPAN",
label = "Choose patient",
choices = df,
selected = NULL),
submitButton(text = "Submit", icon = NULL)),
mainPanel(
dataTableOutput("tableoutput")
)
)
))
server.R
Server script should take the input and query the data from the table
Render the selected data to UI
If I change value in UI then it should display selected input data.
library(RODBC)
shinyServer(
function(input, output) {
dbconnect <- odbcConnect("orecloud", uid="oracle", pwd="Edvenswa2016", believeNRows=FALSE)
df2 <- data.frame()
input_var <- input$CPAN
print (input_var)
my_query <- paste("select * from CYTOKINE where CPAN= ", input_var)
print(myquery)
df2 <- sqlQuery(dbconnect,myquery)
output$tableoutput <- renderDataTable({df2})
}
)
You need to do it reactive
df2=reactive({
input_var <- input$CPAN
my_query <- paste("select * from CYTOKINE where CPAN= ", input_var)
sqlQuery(dbconnect,myquery)
})
and use like renderDataTable({df2()}) } )
If input$CPAN is character you need paste0("select * from CYTOKINE where CPAN= '", input_var,"'")
Also dont forget disconect
session$onSessionEnded(function() {
odbcClose(dbconnect )
})
I'm very new to shiny and am having some trouble and have been searching all day, so hopefully someone can help me. Once an action button (actionButton, on UI) is selected by a user, I would like the server script to call a function (evenReactive in server) I wrote (myfunction, see below) that uses the input items from the UI and gets the right parameters I need to run myfunction and produce a n X2 data matrix that will be plotted as a table (renderTable in server, below). The data is a n X 2 matrix.
I have some sample code below. It's not the entre code, so you will not see the UI with the inputs I am putting in my function, or the server parts associated. But, it is the part I am trying to fix. I hope that's ok. I don't need the renderText, but when I take it out I get an error. Sorry for the formatting. Copy and pasting changed it a bit.
library(shiny)
ui <- shinyUI(fluidPage
(column(4,actionButton("gobutton", "Run"),verbatimTextOutput("ntext1")),
column(4, DT::dataTableOutput("table",width = "75%"))))
library(shiny)
shinyServer(function(input, output, session)
ntext1 <- eventReactive(input$gobutton, {
if (input$gobutton==1){
data=myfunction(input$checkbox,input$dateRange)}
})
output$ntext1 <- renderText({ntext1()})
output$table <- DT::renderDataTable(DT::datatable({
data
})
))
myfunction <-function(All,date1,date2,source_cd,tran_cd,airline_list,mag_level) {
print(All); print(date1); print(date2); print(source_cd);print(tran_cd);print(airline_list);print(mag_level)
setwd("C:/Users/TRomano/Documents/Projects/TrendAnalysis/Data")
data = read.csv("Airlines.csv",header = TRUE)
return(data)
}
For this type of problem I like to make use of reactiveValues()that are designed to store data in a reactive way.
Here is a simple app (single app, not split into server & ui) that demonstrates what I think you are trying to do
library(shiny)
library(DT)
ui <- shinyUI(
fluidPage(
column(width = 4,
actionButton("gobutton", "Run")
column(width = 4,
DT::dataTableOutput("table",
width = "75%"))))
server <- shinyServer(function(input, output, session){
rv <- reactiveValues()
rv$data <- NULL
observe({ ## will 'observe' the button press
if(input$gobutton){
print("here") ## for debugging
rv$data <- myfunction() ## store the data in the reactive value
rv$data
}
})
output$table <- DT::renderDataTable({
## The data has been stored in our rv, so can just return it here
rv$data
})
})
myfunction <- function(){
data <- data.frame(id = c(1,2,3),
val = letters[1:3])
return(data)
}
shinyApp(ui, server)
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Company Name"),
dashboardSidebar(sidebarMenu(
menuItem("Results Table", tabName = "ResultsTable", icon = icon
("ResultsTable")),
dashboardBody(
tabItems(
tabItem(tabName tabItem(tabName = "ResultsTable",
fluidPage(
headerPanel(
fluidRow(
column(4,
selectInput("sour",
"Source Type:",
c("All",
unique(as.character(data_source_cd)))), offset=2
),
column(4,
selectInput("tran",
"Transaction Type:",
c("All",
unique(as.character(tran_cd)))))),
# Create a new row for the table.
fluidRow(column(8, DT::dataTableOutput("table",width = "75%"),offset = 2))))))
library(shiny)
shinyServer(function(input, output, session) {
ntext1 <- eventReactive(input$gobutton, {
if (input$dateRange[2]<input$dateRange[1]){print("You selected the date range option;however, the end date entered occurs before the starting date")}else{
output$ntext1 <- renderText({print("Analysis complete...")});
observe({
if(input$gobutton){
rv$data <- myfunction() }
})
output$table <- DT::renderDataTable(DT::datatable({
data <- rv$data
if (input$sour != "All") {
data <- data[data[,5] == input$sour,]
}else{data}
if (input$tran != "All") {
data <-data[data[,6] == input$tran,]
}else{data}
}))
}})
Once an action button is selected on the main page of my dashboard(not shown), myfunction runs analysis with the inputs from the main dashboard page. On another tab, a table will show once the analysis is complete. There are drop down menus (input$tran, input$sour) that will reduce what is in the table depending on what the user selects. If there are any errors in the input, a warning of text comes up on the main dashboard page and the tab with the table will not be created until the correct inputs are selected.
The observe function allowed me to run my function and the output data of the function set to a variable I could later use to create the table (shown).
THis is my first time posting. Any questions feel free to ask.