I have below 3 files (Retrieve_AOI_Utilization.R, ui.R, server.R)
# Retrieve_AOI_Utilization.R
library(lubridate)
library(RODBC)
myconn<- odbcConnect("pfods", uid = "testingt", pwd = "****")
systemtype <- '0043-004'
startDate <- "08/12/2014" # DD/MM/YYYY format
endDate <- "11/12/2014" # DD/MM/YYYY format
TimeDiff <- as.Date(as.character(endDate), format="%d/%m/%Y")- as.Date(as.character(startDate), format="%d/%m/%Y")
TimeDiff <-as.data.frame(TimeDiff)
nDays <- TimeDiff$TimeDiff[[1]]
conveyortime <- 25
querytest <- paste("SELECT distinct MONO, LASTUPDATE, SYSTEMTYPE, TESTTIME
FROM PFODS.PPLPRODUCTAOI
WHERE SYSTEMTYPE = '",systemtype,"'
AND LASTUPDATE >= todate('",startDate,"','DD/MM/YYYY')
AND LASTUPDATE <= todate('",endDate,"','DD/MM/YYYY')
AND TESTTIME IS NOT NULL
ORDER BY LASTUPDATE ASC, MONO" , sep="")
test <- sqlQuery(myconn, query_test)
testtime <- test$TESTTIME
HourMinSec <-strftime(testtime, format="%H:%M:%S")
TotalTimeInSec <- periodtoseconds(hms(HourMinSec)) # convert to total seconds
Utilization = (sum(TotalTimeInSec) + nrow(test)conveyor_time)/ (nDays24*3600) *100
# ui.R
shinyUI(fluidPage(
titlePanel("TestSystem Utilization for AOI Machines in SMT."),
sidebarLayout(
sidebarPanel(
helpText("Select a TestSystem and Date Range and press Submit button to retrieve its Utilization value."),
selectInput("var",
label = "Select a TestSystem",
choices = list("0043-001","0043-002","0043-003","0043-004","0043-A067-001","0043-A067- 003"),
selected = "0043-001")
),
mainPanel(
textOutput("text1")
)
)
))
# server.R
Utilization <- source('Retrieve_AOI_Utilization.R')
shinyServer(
function(input, output) {
#Utilization <- 50
specify_decimal <- function(x, k) format(round(x, k), nsmall=k)
output$text1 <- renderText({
paste("TestSystem", input$var, "has Utilization value of", specify_decimal(Utilization$value, 2),"%")
})
}
)
If I retrieve Utilization value directly from Utilization <- 50, the application runs perfectly OK in Shiny Server.
I see that in the localhost, it is working, when the Utilization value is retrieved from "Utilization <- source('Retrieve_AOI_Utilization.R')" , see printscreen below:
http://imgur.com/8h24p5h
But if I retrieve Utilization value from source('Retrieve_AOI_Utilization.R'), and deployed to the Shiny server, the application hangs with a grey screen, as seen below:
http://imgur.com/BcqwMfb
Why is this so?
Please help.
Firstly, do you have two different files: Retrieve_AOI_Utilization.R and RetrieveAOIUtilization.R? Are you using both on purpose, or are you supposed to be using one? Because you have only shown the code for the latter one.
Secondly, if you press F12 on your browser when it crashes on shiny server, and go to the "Console" tab, the line of your R code which breaks could be displayed there. You can debug from this point.
Edit
You have the following connection:
myconn<- odbcConnect("pfods", uid = "testingt", pwd = "****")
Are you certain that you can connect to the pfods ODBC connector from where you are hosting shiny-server? Be sure to have the identical ODBC, database, username and password.
Related
Good evening.
I would like to use the ichimiko package for an interactive visualization in r shiny.
I would like that every time the user choose a sticker, the graphic can change automatically.
When I put the code in the ui interface I get the following error ('cloud not existing').
But if I save the code of the cloud (here stock = "AAPL") before running the shinyApp, the code work Well. I get the graphic but the plot is very great 0
ichimoku(getSymbols("AAPL", src = "yahoo", from=start_date, to=end_date, auto.assign=F))-> cloud
Below is the code.
library(ichimoku)
library(shiny)
library(quantmod)
start_date <- Sys.Date()-365
end_date <- Sys.Date()
ui <- fluidPage("Stock market",
titlePanel("Stop market App"),
sidebarLayout(
sidebarPanel(
textInput("Stock","Input Stock"),
selectInput("Stock", label = "Stock :", choices = c("DIA",
"MSFT",
"FB",
"AAPL",
"GOOG"), selected = "AAPL", multiple = FALSE),
actionButton("GO","GO")),
mainPanel(br(),
h2(align = "center", strong("ICHIMOKU CLOUD PLOT")),
iplot(cloud, width = 1000, height = 1000)
)))
server <- function(input, output, session){
cs <- new.env()
data <- eventReactive(input$GO,{
req(input$Stock)
getSymbols(input$Stock, src = "yahoo",
from=start_date, to=end_date, auto.assign=F)
})
cloud1 <- reactive({
dt<- data()
cloud <- ichimoku(dt)
})
cloud <- ichimoku(cloud1(), ticker = input$Stock)
}
shinyApp(ui = ui, server = server)
IS it also possible to fix the bslib at the left and down side?
Try to create the "iplot()" object in the server and call it in the ui with plotOutput()?
I am trying to write an input page that takes the date of a section's last training, then calculates the currency of that training (how many days since), but I seem to be having a problem accessing the date from the dateInput element. I'm currently just trying to get it to print, but it is eluding me. Is there something I'm missing, or how can I get this to work? I've commented out the code to (hopefully) calculate the date gap, as I haven't had a date to work through that just yet. If you see an issue there, I'd appreciate that pointer as well.
Thank you!
library(shiny)
ui <- fluidPage(
tags$h3("Section Training"),
dateInput("section_Last_Training",
"When was your last training course?",
daysofweekdisabled = c(0, 6),
max = Sys.Date()
),
)
server <- function(input, output, session) {
section_Last_Training <- reactive({
# dateGap = as.character(difftime(Sys.time(), input$section_Last_Training, units = "days"))
print(input$section_Last_Training)
})
}
shinyApp(ui, server)
It is working, just make sure the last value in reactive is the value you want to assign to the reactive. You can do print, but do it before your gap calculation. Another thing is reactive is "lazily" evaluated. It means if there is no downstream reactivity requires it, it will not be calculated. So you need to add some events that require this reactive to make it work. See the code below.
library(shiny)
ui <- fluidPage(
tags$h3("Section Training"),
dateInput("section_Last_Training",
"When was your last training course?",
daysofweekdisabled = c(0, 6),
max = Sys.Date()
),
)
server <- function(input, output, session) {
section_Last_Training <- reactive({
print(input$section_Last_Training)
as.character(difftime(Sys.time(), input$section_Last_Training, units = "days"))
})
observe(print(section_Last_Training()))
}
shinyApp(ui, server)
I'm working on leaflet with shiny. The tools is basic, i have a map with some markers (coming from a table with LONG and LAT).
What I want to do is to open a table or a graph when i click on the marker.
Is there a simple way to do it?
Do you have a really simple example: you have a maker on a map, you click on the marker, and there is a plot or a table or jpeg that s opening?
Here is another example, taken from here and a little bit adapted. When you click on a marker, the table below will change accordingly.
Apart from that, a good resource is this manual here:
https://rstudio.github.io/leaflet/shiny.html
library(leaflet)
library(shiny)
myData <- data.frame(
lat = c(54.406486, 53.406486),
lng = c(-2.925284, -1.925284),
id = c(1,2)
)
ui <- fluidPage(
leafletOutput("map"),
p(),
tableOutput("myTable")
)
server <- shinyServer(function(input, output) {
data <- reactiveValues(clickedMarker=NULL)
# produce the basic leaflet map with single marker
output$map <- renderLeaflet(
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addCircleMarkers(lat = myData$lat, lng = myData$lng, layerId = myData$id)
)
# observe the marker click info and print to console when it is changed.
observeEvent(input$map_marker_click,{
print("observed map_marker_click")
data$clickedMarker <- input$map_marker_click
print(data$clickedMarker)
output$myTable <- renderTable({
return(
subset(myData,id == data$clickedMarker$id)
)
})
})
})
shinyApp(ui, server)
There is a leaflet example file here:
https://github.com/rstudio/shiny-examples/blob/ca20e6b3a6be9d5e75cfb2fcba12dd02384d49e3/063-superzip-example/server.R
# When map is clicked, show a popup with city info
observe({
leafletProxy("map") %>% clearPopups()
event <- input$map_shape_click
if (is.null(event))
return()
isolate({
showZipcodePopup(event$id, event$lat, event$lng)
})
})
Online demo (see what happens when you click on a bubble):
http://shiny.rstudio.com/gallery/superzip-example.html
On the client side, whenever a click on a marker takes place, JavaScript takes this event and communicates with the Shiny server-side which can handle it as input$map_shape_click.
I'm trying to use shiny to create a bar graph for a state that is selected via drop-down box. I'm quite new to R and I've tried a variety of examples to no avail. I have three variables (state, claim #, total $) and for each state there are five values. So something like this:
state <- c("PA", "TX", "NY")
claim_num <- c(1:15)
total <- sample(1000:5000, 15)
df <- (state, claim_num, total)
I want to have something similar to https://beta.rstudioconnect.com/jjallaire/shiny-embedding/#inline-app but I don't know if I can format my data in that was since I would have a lot of NAs.
Do you mean something like this (you can download and run the example)?
library(shiny)
ui <- shinyUI(
fluidPage(
titlePanel("Sample Shiny App"),
sidebarLayout(
sidebarPanel(
uiOutput("stateInput")
),
mainPanel(
plotOutput("statePlot")
)
)
))
server <- shinyServer(function(input, output) {
state <- sample(state.abb, 3, replace = FALSE)
total <- sample(1000:5000, 15)
claimNumber <- 1:15
data <- data.frame(state, total, claimNumber)
output$stateInput <- renderUI({
selectInput(
inputId = "state",
label = "Select a State:",
choices = levels(data$state)
)
})
output$statePlot <- renderPlot({
hist(data$total[data$state == input$state])
})
})
shinyApp(ui = ui, server = server)
What we're doing is taking the list of unique states available in our data frame and passing those to our selectInput that renders as a dropdown in the UI. From here, we can access whatever value the user has selected through the input$state object. More generally, we can access inputs based on whatever we define the inputId to be (in this particular case, we call it state).
Having grabbed the user input, we can then subset the data frame to only return values that correspond to the user-defined state and, in this case, pass those totals values to a plot that we render as output.
In an attempt to solve this question
R Shiny: display elapsed time while function is running,
I tried several things, and I have questions about the modal dialog.
Here is a MWE
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
actionButton('run', 'Run')
),
mainPanel(
tableOutput("result")
)
)
)
server <- function(input, output) {
N <- 4
rv_time <- reactiveValues(
startTime = Sys.time(),
endTime = Sys.time()
)
output$start <- renderUI({
line1 <- paste("Start at:", format(Sys.time(), format = "%R"))
line2 <- "Be patient, it can takes some time"
HTML(paste(line1, line2, sep = "<br/>"))
})
result_val <- reactiveVal()
observeEvent(input$run,{
showModal(modalDialog(htmlOutput("start"), footer = NULL))
rv_time$startTime <- Sys.time()
result_val(NULL)
for(i in 1:N){
# Long Running Task
Sys.sleep(1)
}
result_val(quantile(rnorm(1000)))
rv_time$endTime <- Sys.time()
# removeModal()
showModal(modalDialog(textOutput("timer"), footer = modalButton("Cancel")))
})
output$result <- renderTable({
result_val()
})
output$timer <- renderText({
paste0("Executed in: ", round(difftime(rv_time$endTime, rv_time$startTime, units = "mins"),2), " minutes")
})
}
shinyApp(ui = ui, server = server)
If you click on the "Run" button the first time, you will see that the first dialog message is empty, the one will the running time works.
If you click another time then on the "Run" button, then everything works. I don't know why this happens.
I could have avoid the call of output$start, and then I would have no problem. But I'd like to understand why it doesn't work, and also, instead of displaying the starting time, I want to display a "dynamical" timer.
Once one clicks on the "Run" button, the dialog box shows the elapsed time since the beginning of the run. So I thought that I need to use an intermediate output$start (I tried to include invalideLater but failed so far). I might be wrong though.
Not related to that, I have a question about difftime. I had to use the option unit = "mins" so I can add the unit behind, because otherwise it doesn't display the unit by default. This example runs in 4 seconds, it would be better than it prints 4 secondes, instead of 0.07 minutes. Is there a way to adapt the unit? (the real code I did runs in several minutes, and possibly hours).
htmlOutput("start") is not calculated when it is hidden. If you add the line
outputOptions(output, "start", suspendWhenHidden = FALSE)
then it will be shown at the first hit on the button.