r - App failed to start - could not find function "setInternet2" - r

I met some problems that whenever I tried to deploy my shiny applications, I got this message: Error in value[3L] : could not find function setInternet2
Calls: local...tryCatch ......
Execution halted
setInternet2
code here
### install packages
library(doParallel)
library(devtools)
library(lattice)
library(shiny)
library(stringr)
library(lubridate)
library(shinyBS)
library(doSNOW)
library(XML)
library(httr)
library(RCurl)
library(wordcloud)
library(tm)
library(rJava)
library(qdap)
library(slam)
runApp(list(
server = shinyServer(function(input, output, session){
observeEvent(input$getNews, {
output$News <- renderDataTable({
# Create a Progress object
progress <- shiny::Progress$new(session, min=1, max=15)
progress$set(message = "(╯ ̄▽ ̄)╯ Loading...", value = 0)
# Close the progress when this reactive exits (even if there's an error)
on.exit(progress$close())
data <- list()
tmp <- paste('.html', sep='')
url <- paste('https://www.ptt.cc/bbs/Stock/index', tmp, sep='')
html <- httr:::content(GET(url), encoding = "UTF-8") # xml2
html <- XML::xmlParse(html) # parse from xml2 to xml
url.list <- xpathSApply(html, "//div[#class='title']/a[#href]", xmlAttrs)
data <- rbind(data, paste('https://www.ptt.cc', url.list, sep=''))
data <- unlist(data)
# cl = makeCluster(rep('localhost', 8), 'SOCK')
# clusterSetupRNG(cl)
# clusterEvalQ(cl, source('R/R/GET.R'))
getDoc <- function(line){
start <- regexpr('www', line)[1]
end <- regexpr('html', line)[1]
if(start != -1 & end != -1){
url <- substr(line, start, end + 3)
name <- strsplit(url, '/')[[1]][4]
txtName <- gsub('html', 'txt', name)
if(!file.exists(paste0("document/news/", txtName))){
# html <- httr:::content(GET(url, config = set_cookies("over18"="1")), encoding="UTF-8")
html <- httr:::content(GET(url), encoding = "UTF-8")
html <- XML::xmlParse(html)
doc <- xpathSApply(html, "//div[#id='main-content']", xmlValue)
#write(doc, paste0("document/news/", gsub('html', 'txt', name)),
# encoding = "UTF-8")
writeLines(as.character(doc), paste0("document/news/", gsub('html', 'txt', name)),
useBytes=T)
}
}
}
# parSapply(cl, data, getDoc)
# stopCluster(cl)
sapply(data, getDoc)
cl <- makeCluster(4, type = "SOCK")
doSNOW:::registerDoSNOW(cl)
articles <-
foreach(i = 1:length(list.files("document/news/")), .combine = 'c') %dopar% {
readLines(paste0("document/news/", list.files("document/news/")[i]), encoding = "UTF-8")[1]
}
stopCluster(cl)
start = regexpr("新聞", articles)
end = regexpr("2016", articles)
news <- substr(articles, start = start - 1, stop = end + 3)[start != -1]
news
news2 <- substr(news, start = 1, stop = regexpr("時間", news) - 1)
# for messages
Sys.setenv(LANG = "Zh_TW")
Sys.setlocale("LC_ALL", "cht")
start = regexpr("時間", news)
end = regexpr("2016", news)
newsDate = substr(news, start = start + 6, stop = end + 3)
newsDate
Sys.setenv(LANG = "en")
Sys.setlocale("LC_ALL", "English")
newsDate = strptime(newsDate, format = "%b %d %H:%M:%S %Y")
newsDate = as.POSIXct(newsDate)
#newsDate = as.Date(newsDate, format = "%b %d %Y")
Sys.setenv(LANG = "Zh_TW")
Sys.setlocale("LC_ALL", "cht")
newsDF <- data.frame(Date = newsDate, Event = news2)
news <- newsDF
news <- news[order(news$Date, decreasing = TRUE), ]
news[as.Date(news$Date, format = "%b %d %Y") >= input$dateRange[1] &
as.Date(news$Date, format = "%b %d %Y") <= input$dateRange[2], ]
})
})
}),
ui = shinyUI(tagList(
tags$head(tags$script(HTML("Shiny.addCustomMessageHandler('closeWindow', function(m) {window.close();});"))),
navbarPage(
"MynavbarPage", inverse = TRUE, id = "navbar",
tabPanel("News",
sidebarLayout(
sidebarPanel(
width = 3,
bsTooltip("stocks", title = "Please enter stock code from yahoo finance.", placement = "bottom", trigger = "hover", options = NULL),
textInput("stocks", label = "Stock Code", value = "2330.TW"),
bsTooltip("dateRange", title = "This is a time period you apply WFA to.", placement = "bottom", trigger = "hover", options = NULL),
dateRangeInput("dateRange", label = "Choose Period", start = "2015-01-01", end = Sys.Date()),
actionButton("getNews", "Start", class="btn-primary btn-lg")
),
mainPanel(
bootstrapPage(
dataTableOutput("News"))
)
))
)))
))
But I can run my App locally. I was wondering if it had anything to do with my local path settings? My app is in a folder, e.g., "MyAPP" where ui.R and server.R are included. I also have another folder named "document" inside MyAPP. I used lots of list.file("document/").
I didn't include setInternet2 function in my app but I was using web APIs such as httr, XML, tm, etc.
Any suggestions?
Many thanks.

It seems that the following command connects to the internet and downloads the data. And internally it is setting the Internet options
html <- httr:::content(GET(url), encoding = "UTF-8") # xml2
Can you try the following which will help you debug
Instead of downloading the HTMl from the internet, read from a file
If it works then we know for sure that code that fetches data from the internet is the issue
Regards,
Anant

Related

Function Not returning results on Shiny App

I wrote this function below:
leg.rpps = function(es, municipio) {
est = as.character(es)
mun = as.character(municipio)
url = paste0("https://apicadprev.economia.gov.br/RPPS_REGIME_PREVIDENCIARIO?sg_uf=",
est, "&no_ente=", curlEscape(mun), "&")
tmp = tempfile()
hdl = curl::new_handle(ssl_verifypeer = 0)
curl::curl_download(url, destfile = tmp, handle = hdl)
tpdt = fromJSON(tmp)
dt1 = (tpdt$results)
dt2 = dt1$data
dt.real = dt2[[1]]
rm(tpdt, tmp, dt1, dt2)
dados = cbind(dt.real$sg_uf, dt.real$no_ente, dt.real$no_tipo_legislacao,
dt.real$nr_legislacao, dt.real$dt_legislacao, dt.real$te_ementa)
colnames(dados) = c("UF", "Ente", "Tipo Legal", "No. Dispositivo",
"Data Publicação", "Ementa")
return(datatable(dados))
}
it works fine by itself, generating the expected results. But when I try to build a shiny app and call it , I get no results at all. The shiny page just stays blank where the data table was supposed to appear. Below is the code for my app (I must say that I'm a beginner on shiny, so I might be f'in up some shiny-related code)
library(shiny)
library(DT)
library(curl)
library(jsonlite)
library(RCurl)
ui <- fluidPage(
titlePanel("Legislação RPPS por Ente"),
sidebarLayout(
sidebarPanel(
textInput(inputId = "estado",
label = "Estado - Sigla:",
value = ""),
textInput(inputId = "municipio",
label = "Município:",
value = ""),
actionButton(
inputId = "click_go",
label = "Ir")
),
mainPanel(
h1("Legislação RPPS"),
h4("Utilizar sigla do Estado (Em maiúscula) e Nome do Município com as
iniciais em Maiúscula"),
dataTableOutput("tabela")
)
)
)
server <- function(input, output) {
leg.rpps = function(es, municipio){
url = paste0("https://apicadprev.economia.gov.br/RPPS_REGIME_PREVIDENCIARIO?sg_uf=",
es, "&no_ente=", curlEscape(municipio), "&")
tmp = tempfile()
hdl = curl::new_handle(ssl_verifypeer = 0)
curl::curl_download(url, destfile = tmp, handle = hdl)
tpdt = fromJSON(tmp)
dt1 = (tpdt$results)
dt2 = dt1$data
dt.real = dt2[[1]]
rm(tpdt, tmp, dt1, dt2)
dados = cbind(dt.real$sg_uf, dt.real$no_ente, dt.real$no_tipo_legislacao,
dt.real$nr_legislacao, dt.real$dt_legislacao, dt.real$te_ementa)
#colnames(dados) = c("UF", "Ente", "Tipo Legal", "No. Dispositivo",
# "Data Publicação", "Ementa")
#return(datatable(dados))
datatable(dados)
}
current_data = eventReactive(
input$click_go,
leg.rpps(input$estado, input$municipio)
)
output$tabela <- renderDataTable({
req(input$click_go)
current_data()
})
}
shinyApp(ui, server)
I'm having a really hard-time to figure out what might be wrong with this. If anyone can even point me out a way out of this, I will be very grateful.
Apparently, I was calling a datatable on another datatable.
when I changed datatable(dados) to dados on leg.rpps() outcome, it worked.

How to solve the error in highcharOutput in shiny tool?

I'm working on cancer data from TCGA.
Im new to shiny and creating web applications (learning it!!)
I'm working on a shiny tool to plot the volcanoplot using highcharter package.
sometimes I'm successfully able to plot the volcanoplot in the UI. but sometimes it fails to plot it and throws an error saying,
"An error has occurred!
could not find function "highchartOutput"
and one warning message is given for the error;
Listening on http://127.0.0.1:5335
Warning: Error in highchartOutput: could not find function "highchartOutput"
83: dots_list
82: div
81: tabPanel
I think there is some problem with the tabset panel.
is this error has anything to do with indentation? (wherever I adjust the brackets it works magically. not sure how it works for sometimes.)
I am attaching the UI and server files with this post.
code is attached for one type of comparison
UI file below:
library(shiny)
# Define UI for application
shinyUI(fluidPage(
# Application title
titlePanel("miR-Gyn-Explorer"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
## select the count matrix
selectInput("file", label = h3("Count Matrix"),
choices = list("Stage I - Normal" = list("TCGA-BRCA" = "Data/TCGA-BRCASI_NT.rda", "TCGA-UCEC" = "Data/TCGA-UCECSI_NT.rda"))),
## select the phenodata of samples
selectInput("phenofile", label = h3("Sample Phenodata"),
choices = list("Stage I - Normal" = list("TCGA-BRCA" = "Data/TCGA-BRCA_phenoSI_NT.rda", "TCGA-UCEC" = "Data/TCGA-UCEC_phenoSI_NT.rda"))),
submitButton("Update View")
),
# Show a plot of the generated distribution
mainPanel(
tabsetPanel(
tabPanel("DEmiRNA", DT::dataTableOutput("DEmiRNA"),
"Volcano-Plot", highchartOutput("volcanoPlot", height = "500px"))
#tabPanel("miRNA-Targets", DT::dataTableOutput('miRTarget'),
#plotOutput("GO"))
)
)
)
)
)
server file:
library(shiny)
library(R.utils)
##function to find the DEmiRNA by edgeR method
library(limma)
library(edgeR)
library(DT)
library(dplyr)
library(multiMiR)
library(miRBaseConverter)
library(ggplot2)
#library(ggrepel)
library(tidyverse)
library(highcharter)
library(org.Hs.eg.db)
library(clusterProfiler)
library(purrr)
gdcDEmiRNA <- function(counts, groups, comparison, filter=TRUE) {
## method = edgeR
dge = DGEList(counts = counts, samples = groups)
group <- factor(groups$group)
design <- model.matrix(~0+group)
colnames(design) <- levels(group)
contrast.matrix <- makeContrasts(contrasts=comparison,
levels=design)
keep = filterByExpr(dge,design)
dge <- dge[keep,,keep.lib.sizes = TRUE]
dge <- calcNormFactors(dge)
dge <- estimateDisp(dge, design)
fit <- glmFit(dge, design)
lrt <- glmLRT(fit, contrast=contrast.matrix)
DEGAll <- lrt$table
DEGAll$FDR <- p.adjust(DEGAll$PValue, method = 'fdr')
o <- order(DEGAll$FDR)
DEGAll <- DEGAll[o,]
return (DEGAll)
}
# Define server logic required to perform the DEmiRNA analysis
server <- function(input, output) {
d <- reactive({
#DEmiRNA calculation
file <- load(input$file)
phenofile <- load(input$phenofile)
if(file == "SI_NT"){
if(phenofile == "phenoSI_NT"){
DEmiRNA <- gdcDEmiRNA(counts = SI_NT, groups = phenoSI_NT,
comparison = 'StageI-Normal')
}
}
})
output$DEmiRNA <- DT::renderDataTable({
mir <- d()
#mir <- mir[mir$FDR < input$FDR,]
})
output$volcanoPlot <- renderHighchart({
x <- d()
x$mirna <- rownames(x)
x$sig <- ifelse(x$PValue < 0.05 & abs(x$logFC) > 0.57, "DEmiRNA", "Not Regulated")
hc <- highchart() %>%
hc_add_series(x, "scatter", hcaes(logFC, -log10(PValue), group = sig, value = mirna),
color = c('rgba(67, 67, 72, 0.6)', 'rgba(124, 181, 236, 0.6)'),
enableMouseTracking = c(TRUE, TRUE),
showInLegend = TRUE, marker = list(radius = 4)) %>%
hc_tooltip(pointFormat = "{point.value}", headerFormat = "") %>%
hc_xAxis(title = list(text = "Log fold change"), gridLineWidth = 1,
tickLength = 0, startOnTick = "true", endOnTick = "true", min = -6, max = 6) %>%
hc_yAxis(title = list(text = "-Log10(p-value)")) %>%
hc_chart(zoomType = "xy", width=700) %>%
hc_exporting(enabled = TRUE, filename = "volcano")
hc
})
}
any comment and help from you guys is appreciated
Thank you in advance!
-Ankita

Invoke function within RShiny server call and render result as print output

I have written a script which makes use of 2 functions in order to calculate the duration required for a test to run, eg power analysis.
Inputs and code as follows;
## RUN POWER CALCULATION
average_daily_traffic <- 3515/30
control <- 0.47
uplift <- 0.02
num_vars <- 2
sample_size_calculator <- function(control, uplift){
variant <- (uplift + 1) * control
baseline <- ES.h(control, variant)
sample_size_output <- pwr.p.test(h = baseline,
n = ,
sig.level = 0.05,
power = 0.8)
if(variant >= 0)
{return(sample_size_output)}
else
{paste("N/A")}
}
## RUN DAYS CALCULATOR FUNCTION
days_calculator <- function(sample_size_output, average_daily_traffic){
days_required <- c((sample_size_output)*num_vars)/(average_daily_traffic)
if(days_required >= 0)
{paste0("It will take ", round(days_required, digits = 0)*num_vars, " days for this test to reach significance, with a daily average of " , round(average_daily_traffic, digits = 0), " visitors to this page over a 30 day period.")}
else
{paste("N/A")}
}
## RUN FUNCTIONS AND OUTPUT ANSWER
sample_size_calculator <- sample_size_calculator(control, uplift)
sample_size_output <- sample_size_calculator$n
answer <- days_calculator(sample_size_output, average_daily_traffic)
answer
This code is performant and is fit for my purpose in a standalone R script.
However, I need to make these functions executable from within a Shiny app. My attempt is as follows;
library(shiny)
ui <- fluidPage(
actionButton("exe", "Run",
style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
mainPanel(
textOutput("answer")
))
server <- function(input, output, session) {
sample_size_calculator <- eventReactive(input$exe,{
average_daily_traffic <- 3515/30
control <- 0.47
uplift <- 0.02
num_vars <- 2
variant <- (uplift + 1) * control
baseline <- ES.h(control, variant)
sample_size_output <- pwr.p.test(h = baseline,
n = ,
sig.level = 0.05,
power = 0.8)
if(variant >= 0)
{return(sample_size_output)}
else
{paste("N/A")}
})
days_calculator <- eventReactive (input$exe,{
days_required <- c((sample_size_output)*num_vars)/(average_daily_traffic)
if(days_required >= 0)
{paste0("It will take approximately ", round(days_required, digits = 0)*num_vars, " days or ", round((round(days_required, digits = 0)*num_vars)/365, digits = 1) ," years for this test to reach significance, based on a daily average of " , round(average_daily_traffic, digits = 0), " users to this page in the last 30 days.")}
else
{paste("N/A")}
})
outputs_ <- eventReactive( input$exe, {
req(sample_size_calculator())
req(days_calculator())
sample_size_calculator <- sample_size_calculator(control, uplift)
sample_size_output <- sample_size_calculator$n
answer <- days_calculator(sample_size_output, average_daily_traffic)
output$answer <- renderText(outputs_$answer)
})
}
shinyApp(ui = ui, server = server)
When I run this code, I see the execute button but no output is displayed.
This is very likely due to a limitation in my understanding of how Shiny invokes functions so if there is a better way I would be very grateful to hear it.
Thanks in advance.
* EDITING TO INCLUDE FULL FUNCTIONALITY CODE *
The objective of the code is to use Mark Edmonson's googleAnalyticsR and googleAuthR to enable retrieval of web visit data to a particular URL/page from the Google Analytics account for last 30days and show a trend of this data. This works fine, once the user enters the URL and hits 'Run'.
There is an additional GA call which retrieves additional data for a particular conversion action (see other_data). This is required in order to derive the conversion rate that is used later in the power calculation.
The calculation is cvr <- aeng$users/totalusers
#options(shiny.port = 1221)
## REQUIRED LIBS
library(shiny)
library(googleAnalyticsR)
library(plotly)
library(googleAuthR)
library(markdown)
library(pwr)
gar_set_client(scopes = c("https://www.googleapis.com/auth/analytics.readonly"))
daterange <- function(x) {
as.Date(format(x, "%Y-%m-01"))
}
## DATE PARAMETERS
date_start <- as.Date(Sys.Date(),format='%d-%B-%Y')-31
date_end <- as.Date(Sys.Date(),format='%d-%B-%Y')-1
date_range <- c(date_start, date_end)
## UI SECTION
ui <- fluidPage(
googleAuth_jsUI("auth"),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "dur_calc.css")
),
tags$br(),
sidebarLayout(
sidebarPanel(
code("To begin, select from 'Accounts' and enter URL of page to be tested:"),
tags$p(),
column(width = 12, authDropdownUI("auth_dropdown",
inColumns = FALSE)),
textInput("url", label = h5(strong("Page to be tested")), value = "Enter full page URL..."),
hr(),
fluidRow(column(3, verbatimTextOutput("value")
)
),
actionButton("exe", "Run Calculator",
style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
),
mainPanel(
plotlyOutput("trend_plot"),
textOutput("page"),
textOutput("answer")
)
)
)
## SERVER SECTION
server <- function(input, output, session) {
auth <- callModule(googleAuth_js, "auth")
## GET GA ACCOUNTS
ga_accounts <- reactive({
req(auth()
)
with_shiny(
ga_account_list,
shiny_access_token = auth()
)
})
view_id <- callModule(authDropdown, "auth_dropdown",
ga.table = ga_accounts)
ga_data <- eventReactive( input$exe, {
x <- input$url
#reactive expression
output$page <- renderText({
paste("You have selected the page:", input$url) })
filterPageurl <- dim_filter("dimension97" , "REGEX", x ,not = FALSE)
filts <- filter_clause_ga4(list( filterPageurl))
req(view_id())
req(date_range)
with_shiny(
google_analytics,
view_id(),
date_range = date_range,
dimensions = "date",
metrics = "users",
dim_filters = filts,
max = -1,
shiny_access_token = auth()
)
})
other_data <- eventReactive( input$exe, {
x <- input$url
filterPageurl <- dim_filter("dimension97" , "REGEX", x ,not = FALSE)
filts <- filter_clause_ga4(list( filterPageurl))
seg_id <- "gaid::uzKGvjpFS_Oa2IRh6m3ACg" #AEUs
seg_obj <- segment_ga4("AEUs", segment_id = seg_id)
req(view_id())
req(date_range)
#req(filts)
with_shiny(
google_analytics,
view_id(),
date_range = date_range,
dimensions = "date",
metrics = "users",
dim_filters = filts,
segments = seg_obj,
max = -1,
shiny_access_token = auth()
)
})
outputly <- eventReactive( input$exe, {
req(other_data())
req(ga_data())
aeng <- other_data()
ga_data <- ga_data()
totalusers <<- sum(ga_data$users)
cvr <- aeng$users/totalusers
average_daily_traffic <- totalusers/30
control <- cvr
uplift <- 0.02
num_vars <- 2
})
sample_size_calculator <- eventReactive(input$exe,{
variant <- (uplift + 1) * control
baseline <- ES.h(control, variant)
sample_size_output <- pwr.p.test(h = baseline,
n = ,
sig.level = 0.05,
power = 0.8)
if(variant >= 0)
{return(sample_size_output)}
else
{paste("N/A")}
})
days_calculator <- eventReactive (input$exe,{
days_required <- c((sample_size_output)*num_vars)/(average_daily_traffic)
if(days_required >= 0)
{paste0("It will take approximately ", round(days_required, digits = 0)*num_vars, " days or ", round((round(days_required, digits = 0)*num_vars)/365, digits = 1) ," years for this test to reach significance, based on a daily average of " , round(average_daily_traffic, digits = 0), " users to this page in the last 30 days.")}
else
{paste("N/A")}
})
output$trend_plot <- renderPlotly({
req(ga_data())
ga_data <- ga_data()
plot_ly(
x = ga_data$date,
y = ga_data$users,
type = 'scatter',
mode = 'lines') %>%
layout(title = "Page Visitors by Day (last 30 days)",
xaxis=list(title="Date", tickformat='%Y-%m-%d', showgrid=FALSE, showline=TRUE),
yaxis=list(title = "Users", showgrid=FALSE, showline=TRUE)
)
})
calc_answer <- eventReactive(input$exe, {
req(outputly)
outputly <- outputly()
sample_size_calculator <- sample_size_calculator()
sample_size_output <- sample_size_calculator$n
days_calculator(sample_size_output, average_daily_traffic)
})
output$answer <- renderText(calc_answer())
}
shinyApp(ui = ui, server = server)
A few suggestions that may help.
Would start with a simplified shiny app before adding all of the calculations, may be easier to work with for now
Would avoid putting output statements inside of eventReactive. See below for example.
Consider having only one observeEvent or eventReactive for the button press instead of multiple, especially since some function results depend on others.
Right now there are no inputs, so don't need additional reactive expressions. When you add inputs, though, you probably will.
If you haven't already, review the R Studio Shiny tutorial on Action Buttons and Reactivity.
Hope this is helpful in moving forward.
library(shiny)
library(pwr)
ui <- fluidPage(
actionButton("exe", "Run", style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
mainPanel(
textOutput("answer")
)
)
server <- function(input, output, session) {
average_daily_traffic <- 3515/30
control <- 0.47
uplift <- 0.02
num_vars <- 2
sample_size_calculator <- function() {
variant <- (uplift + 1) * control
baseline <- ES.h(control, variant)
sample_size_output <- pwr.p.test(h = baseline,
n = ,
sig.level = 0.05,
power = 0.8)
if(variant >= 0)
{return(sample_size_output)}
else
{return(NA)}
}
days_calculator <- function (sample_size_output, average_daily_traffic) {
days_required <- c((sample_size_output)*num_vars)/(average_daily_traffic)
if(days_required >= 0)
{paste0("It will take approximately ", round(days_required, digits = 0)*num_vars, " days or ", round((round(days_required, digits = 0)*num_vars)/365, digits = 1) ," years for this test to reach significance, based on a daily average of " , round(average_daily_traffic, digits = 0), " users to this page in the last 30 days.")}
else
{paste("N/A")}
}
calc_answer <- eventReactive(input$exe, {
sample_size_calculator <- sample_size_calculator()
sample_size_output <- sample_size_calculator$n
days_calculator(sample_size_output, average_daily_traffic)
})
output$answer <- renderText(calc_answer())
}
shinyApp(ui = ui, server = server)

Reactive contents problem in for loops for R Shiny

I am working on "for loops" in RShiny, I want to plot its result according to selected date. However, I have difficulty in determining reactive contents in server. It didn't worked. Here is my complete code:
dat <- read.csv('C:/Users/10109/Desktop/Alarm/alarm_plant5.CSV',header=T, sep=";")
dat=subset(dat, select = c("SourceName","EventTime" ,"Date"))
dat$Date <- format(as.Date(dat$Date, format = "%m.%d.%Y"), "%Y-%m-%d")
dat$EventTime= paste(dat$Date, dat$Time, sep=" ")
dat$EventTime=as.POSIXct(strptime( dat$EventTime, "%Y-%m-%d %H:%M"), tz = "", origin = '1970-01-01 00:00')
ui <- fluidPage(
titlePanel("Analiz"),
dateRangeInput(inputId="daterange", label = "Tarih" , start = "2017-01-02", end = "2017-12-31", min = "2017-01-02",
max = "2017-12-31", separator = " to "),
verbatimTextOutput("alarmsayisi"),
plotOutput(outputId = "floodplot")
)
server <- function(input, output){
training=reactive({dat%>% filter(as.Date(dat$Date)>=as.Date(input$daterange[1]) & as.Date(dat$Date)<=as.Date(input$daterange[2]) )})
t=0
result=reactive(data.frame())
for (i in seq(reactive(nrow(training())))){
limit2=reactive(training()$EventTime[i]+ minutes(10))
flood_test=reactive(training()%>% filter(training()$EventTime[i] <= training()$EventTime & training()$EventTime <= limit2()))
alarm_number=reactive(nrow(flood_test()))
t=t+1
result[t,1]=reactive(i)
result[t,2]=reactive(input[[training()$EventTime[i]]])
result[t,3]=reactive(input[[alarm_number()]])
}
result()=result()[!duplicated(result()$V2),]
output$floodplot <- renderPlot({
plot(result()$V2, result()$V3, type="l", col= "blue", xlab = "Tarih zaman", ylab = "On dakika icinde calan alarm sayisi",
main = "Alarm flood tahmini")
abline(h=10, col="red", lwd=1.5)
} )
output$alarmsayisi <- renderText({
paste("Toplam alarm sayisi", as.character(nrow(training())))
})
}
shinyApp(ui = ui, server = server)
The errors I encountered are:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
Or
Error in result()[t, 1] = i : invalid (NULL) left side of assignment
I did many trials by changing the variables to reactive or not, but I could not make it work. Could you please help me about this issue? There should be something I interpret wrong.

Conditional Sidebar in a shiny app depending on tab selected

I am trying to build a shiny app where the sidebar is dynamic based on the tab that is selected. The sidebar is populated by a csv file. Right now it is just reading a CSV file named machines.csv. I would want that to be able to read for example austin.csv, dallas.cav based on the tab name. There will be 7 tabs total. Also I am having trouble with the plot area. I want the plot to render to the correct tab (which is always the selected tab).
The code I have is here. The app is at http://45.55.208.171:3838/
Only the first two machines have data right now. And the Dallas tab I can not get to work because it seems I can't use the same render plot ID. Not sure how to make that dynamic based on the tab as well.
library(shiny)
library(ggplot2)
library(scales)
library(grid)
library(RColorBrewer)
library(lubridate)
library(ggrepel)
library(plyr)
library(dplyr)
library(DT)
library(RCurl)
library(readr)
library(stringr)
Machine <-read.csv("machines.csv")
Sys.setenv(TZ="US/Central")
SDate <- Sys.Date()
ui <- fluidPage(
titlePanel("Printer Utilization"),
sidebarLayout(
sidebarPanel(width = 2,
radioButtons("typeInput", "Machine", t(Machine[1]) , width = 4),
dateInput("RepDate", "Date of Report",format = "mm-dd-yyyy",value = "08-03-2016"),
downloadButton("downloadplot", "Download")),
mainPanel(
tabsetPanel(id = "plants",
tabPanel("Austin",value = "Austin", plotOutput("plants",width = "120%",height = "600px")),
tabPanel("Dallas",value = "Dallas", plotOutput("Dallas",width = "120%",height = "600px")),
tabPanel("Table", div(DT::dataTableOutput("log"), style = "font-size:50%")))
)))
server <- function(input, output) {
output$plants <-renderPlot({
Sys.setenv(TZ="US/Central")
SDate <- Sys.Date()
SDate <-as.POSIXct(SDate,format="%Y%m%d")+18000
RepDate.1 <- reactive({ as.POSIXct(input$RepDate,format="%Y%m%d", tz="US/Central")}+18000)
typeInput.1 <- reactive({input$typeInput})
RDate <- RepDate.1()
Machine.1<-reactive({subset(Machine,MNames.i==typeInput.1())})
Serial = Machine.1()$Serial.i
IP = Machine.1()$IP.i
Type = Machine.1()$Type.i
if (Type=="b"){
if (SDate==RepDate.1())
{
extension <- ".ACL"
logdata <- (read.csv(paste(Serial, as.character(RDate,format="%Y%m%d"), extension, sep = "") , sep = ';'))
RDate <- RDate-86400
extension <- ".CSV"
logdata <- (rbind(read.csv(paste(Serial, as.character(RDate,format="%Y%m%d"), extension, sep = "") , sep = ';'),logdata))
}
if (SDate!=RepDate.1())
{
extension <- ".CSV"
try(logdata <- (read.csv(paste(Serial, as.character(RDate,format="%Y%m%d"), extension, sep = "") , sep = ';')))
RDate <-RDate-86400
logdata <- (rbind(read.csv(paste(Serial, as.character(RDate,format="%Y%m%d"), extension, sep = "") , sep = ';'),logdata))
RDate <-RDate+172800
if (RDate==SDate)
{extension <- ".ACL"}
try(logdata <- (rbind(read.csv(paste(Serial, as.character(RDate,format="%Y%m%d"), extension, sep = "") , sep = ';'),logdata)))
}
logdata <- subset(logdata, (startdate == as.character(input$RepDate,format="%Y-%m-%d")) | (readydate == as.character(input$RepDate,format="%Y-%m-%d")))
logdata$jobname <- sub(":.*", "", logdata$jobname)
logdata$starttime.ct <- as.POSIXct(paste(logdata$startdate, logdata$starttime, sep = " ", format = "%Y%m%d %H:%M:%S", tz="US/Central"))
logdata$starttime.ct <- force_tz(logdata$starttime.ct,tzone="US/Central")
logdata$readytime.ct <- as.POSIXct(paste(logdata$readydate, logdata$readytime, sep = " ", format = "%Y%m%d %H:%M:%S", tz="US/Central"))
logdata$readytime.ct <- force_tz(logdata$readytime.ct,tzone="US/Central")
logdata$idletime.ct <- as.POSIXct(logdata$idletime, format = "%H:%M:%S")
logdata$idletime.hour <-as.POSIXlt(logdata$idletime.ct)$hour + as.POSIXlt(logdata$idletime.ct)$min/60 + as.POSIXlt(logdata$idletime.ct)$sec/3600
logdata$activetime.ct <- as.POSIXct(logdata$activetime, format = "%H:%M:%S")
logdata$activetime.hour <-as.POSIXlt(logdata$activetime.ct)$hour + as.POSIXlt(logdata$activetime.ct)$min/60 + as.POSIXlt(logdata$activetime.ct)$sec/3600
Sreadytime <- (strptime(logdata$readytime.ct,format="%Y-%m-%d %H:%M:%S"))
Sstarttime <- (strptime(logdata$starttime.ct,format="%Y-%m-%d %H:%M:%S"))
Rtime <- (Sreadytime-Sstarttime)/3600
Idletime <- (strptime(logdata$idletime.ct,format="%Y-%m-%d %H:%M:%S"))
Utilization <- sum(logdata$activetime.hour/24)
Utilization <- paste(round(Utilization*100,digits=1),"%",sep="")
output <- format(sum(logdata$nofprinteda4bw)+sum(logdata$nofprinteda3bw*2), big.mark=",")
ymax.r = (logdata$idletime.hour/(logdata$idletime.hour+logdata$activetime.hour))
logdata$jobname <- strtrim(logdata$jobname, 18)
}
if (Type=="c"){
url <- paste("http://",IP,"/xjutil/log.csv", sep="")
dat <- readLines(url)
dat <- dat[-1]
dat <- dat[-1]
varnames <- unlist(strsplit(dat[1], ","))
nvar <- length(varnames)
varnames<-make.names(varnames, unique=TRUE)
k <- 1
dat1 <- matrix(NA, ncol = nvar, dimnames = list(NULL, varnames))
while(k <= length(dat)){
k <- k + 1
#if(dat[k] == "") {k <- k + 1
#print(paste("data line", k, "is an empty string"))
if(k > length(dat)) {break}
#}
temp <- dat[k]
# checks if there are enough commas or if the line was broken
while(length(gregexpr(",", temp)[[1]]) < nvar-1){
k <- k + 1
temp <- paste0(temp, dat[k])
}
temp <- unlist(strsplit(temp, ","))
message(k)
dat1 <- rbind(dat1, temp)
}
dat1 = dat1[-1,]
logdata<-as.data.frame(dat1)
logdata$starttime.ct <-strptime(logdata$timestamp.printing,format="%Y %m %d %H %M %S", tz="US/Central")
logdata$readytime.ct <-strptime(logdata$timestamp.done.printing,format="%Y %m %d %H %M %S", tz="US/Central")
logdata$date.timestamp.printing <- as.character(substr(logdata$timestamp.printing, 1, 10))
logdata$date.timestamp.done.printing <- as.character(substr(logdata$timestamp.done.printing, 1, 10))
logdata <- subset(logdata, (date.timestamp.printing == as.character(RepDate.1(), format = "%Y %m %d")) | (date.timestamp.done.printing == as.character(RepDate.1(), format = "%Y %m %d")))
logdata$title <- sub(":.*", "", logdata$title)
logdata$activetime <- logdata$readytime.ct - logdata$starttime.ct
Utilization <- sum(logdata$activetime/86400)
Utilization <- paste(round(Utilization*100,digits=1),"%",sep="")
output<-format(sum(as.numeric(logdata$total.pages.printed)),big.mark = ",")
output<-""
ymax.r = 0
logdata$jobname <- logdata$title
logdata$jobname <- strtrim(logdata$jobname, 18)
}
if (Type=="a"){
url <- paste("http://",IP,"/logs/","?C=M;O=D", sep="")
html <- paste(readLines(url), collapse="\n")
matched <- str_match_all(html, "<a href=\"(1100.*?)\"")
links <- matched[[1]][, 2]
print(links)
for (i in links[1:15])
{
url <- paste("http://",IP,"/logs/", sep="")
url.a <- paste(url,as.character(i) ,sep = "")
print(url.a)
if (exists("logdata")){
logdata <- rbind(read.csv(url.a, header=TRUE, fill = TRUE, sep = ","), logdata)
}
else{
logdata <- read.csv(url.a, header=TRUE, fill = TRUE, sep = ",")
print(url.a)
}
}
logdata$size <- logdata$SqFt
logdata <- logdata %>% distinct(Start.time, .keep_all = TRUE)
logdata$Start.time <- strptime(logdata$Start.time, format="%a %b %d %H:%M:%S %Y")
logdata$Total.time <- as.POSIXlt(logdata$Total.time, format = "%H:%M:%S")
logdata$Total.time <- as.POSIXlt(logdata$Total.time)$hour + as.POSIXlt(logdata$Total.time)$min/60 + as.POSIXlt(logdata$Total.time)$sec/3600
logdata$readytime.ct <- as.POSIXct(logdata$Start.time)+(logdata$Total.time * 3600)
logdata$starttime.ct <- as.POSIXct(logdata$Start.time)
logdata$starttime <- strptime(logdata$starttime.ct,format="%Y-%m-%d")
logdata$End.time <- as.POSIXct(logdata$Start.time)+(logdata$Total.time * 3600)
logdata <- subset(logdata, as.character(starttime,format="%Y-%m-%d") == as.character(RepDate.1(),format="%Y-%m-%d") | (strptime(End.time,format="%Y-%m-%d") == as.character(RepDate.1(),format="%Y-%m-%d")))
Utilization <- (sum(logdata$Total.time))/60
Utilization <- paste(round(Utilization*100,digits=1),"%",sep="")
output<-0
#ymax.r = logdata$SqFt.hr/300
ymax.r = 0
logdata$jobname <- logdata$File.name
}
p<-ggplot(logdata, aes(xmin = starttime.ct, xmax = readytime.ct, ymin = 0, ymax = 1-ymax.r, fill = factor(jobname))) + geom_rect(alpha = .9) +
labs(title=paste(typeInput.1(),RepDate.1(), Utilization, output,sep=" "),x="Time of day",y="Run Time") + theme(legend.position="bottom", legend.title = element_blank(), legend.title = element_text(size=10),legend.title=element_blank()) + guides(fill=guide_legend(nrow=5)) +
scale_x_datetime(labels = date_format("%H:%M", tz="US/Central"),breaks = date_breaks("1 hour"),expand=c(0,0)) +
coord_cartesian(xlim = as.POSIXct(c(RepDate.1()+86400,RepDate.1()),format="%Y%m%d %H:%M:%S", tz="US/Central")) +
scale_y_continuous(labels=percent,expand=c(0,0),limits=c(0,1))
print(p)
file<-ggsave("myplot.pdf",device = "pdf",plot = p,width=16, height=10,paper="special")
})
output$downloadplot <- downloadHandler(
filename="myplot.pdf", # desired file name on client
content=function(con) {
file.copy("myplot.pdf", con)
}
)
outputOptions(output, "downloadplot", suspendWhenHidden=FALSE)
}
shinyApp(ui = ui, server = server)
How about this?
Here, I hardcoded choice_set variable, but I suppose you can define it using external data file.
Keys.
Keep your data in reactiveValues, so it can be referred to from server operations.
Use observeEvent(input$tabset, ...) to trigger server operation only when the tabset value has been changed.
Use updateRadioButtons to change the properties of the input components.
R
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(radioButtons("radio", "radio", c("A", "B"))),
mainPanel(
tabsetPanel(id = "tabset",
tabPanel("alphabet", value = "alpha"),
tabPanel("number", value = "number"))
)))
server <- function(input, output, session)
{
RV <- reactiveValues(
choise_set = list(
alpha = c("A", "B"),
number = c("1", "2", "3")
)
)
observeEvent(input$tabset, {
updateRadioButtons(session, "radio",
choices = RV$choise_set[[input$tabset]])
})
}
runApp(list(ui = ui, server = server))

Resources