Conditional Sidebar in a shiny app depending on tab selected - r

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))

Related

Issue with R-Script populating required content in excel

This script outputs excel spreadsheets of different region. However, since I included a column "Later", changed the corresponding template to also include the column "Later" and increased the number on this line "df <- subset(clist[,c(1:18, 20:29)" from 28 to 29 (given the increased column). The output on the column "group" has come back with its content, but with quotation mark and some instance with CHAR(10).
Is there anyway I can edit this script to have column "group" outcome its content without the quotation marks. Please help!! help! I have struggled with this since. See script below
NB changes made to the original script are as follows
inclusion of later in the sqlcode
changing the df <- subset(clist[,c(1:18, 20:28)" to df <- subset(clist[,c(1:18, 20:29)
Changing the second df <- subset(clist[,c(1:17, 19:28)] to df <- subset(clist[,c(1:18, 20:29)]
#####Constants#####
requiredpackages <- c("XLConnect", "RPostgreSQL", "svDialogs", "getPass")
reqpackages <- function(requiredpackages){
for( i in requiredpackages ){
if( ! require( i , character.only = TRUE ) ) {
install.packages( i , dependencies = TRUE )
library( i , character.only = TRUE )
}
}
}
# set the version to 1.0.5
packageurl <- "https://cran.r-project.org/src/contrib/Archive/XLConnect/XLConnect_1.0.5.tar.gz"
install.packages(packageurl, repos=NULL, type="source")
library(XLConnect)
library(RPostgreSQL)
library(svDialogs)
library(getPass)
source("N:/Ana/Code/Analysiss/Rational/R SQL working/postgresql-avd.R")
#####Retrieve data from analysis server#####
sqlcode <- paste("SELECT concat_ws(';',datacompletion,sortprovider) as datacompletion,ba,outstandingdata,provider,summary,
m,m_hos,m_sur,m_for,m_dob,ed,
bkhos,delhos,
pregnancy,b_d,
b,b_na,
group,groupsw,later,estimated,
screening,date,screening2,
booking,city,use,con,water
FROM common.etl_chasing
where ((date::text like '%",tperiod,"%' or date::text like '%",cperiod,"%')
and (anomalygroup like '%Down%' or group like '%Edwards%' or group like '%Patau%'))
or eddfyear like '%", fperiod,"%' or cleanyear like '%", cperiod, "%'", sep='')
con <- createConnection()
clist <- dbGetQuery(con, sqlcode)
dbDisconnect(con)
#####Create new folder on PID drive to output chasing lists to#####
dirname <- paste("P:/Data/Antenatal/Testing/", Sys.Date(),sep='')
dir.create(dirname)
#####Export CSV of all data#####
write.csv(clist,paste(dirname,"/masterlist.csv",sep=''))
#####Copy template for all individual providers#####
sortproviders <- unique(clist$sortprovider)
inpath <- "P:/Data/National/Antenatal/Template17b.xlsx"
for (i in seq_along(sortproviders)) {
outpath <- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
file.copy(from = inpath, to = outpath)
}
#####Populate templates for individual providers#####
swpatterns <- c("68 - ", "70 - ", "72 - ", "73 - ", "84 - ", "93 - ", "94 - ", "95 - ", "96 - ", "99 - ")
#grepl(paste(swpatterns, collapse = "|"), sortproviders\[1\])
#otherpatterns \<- c("72 - ", "96 - ", "73 - ", "93 - ", "94 - ", "72 - ", "99 - ")
#swsortproviders \<- unique(grep(paste(swpatterns, collapse = "|"), sortproviders, value = TRUE))
#restsortprividers \<- unique(grep(paste(otherpatterns, collapse = "|"), sortproviders, value = TRUE))
for (i in seq_along(sortproviders)) {
outpath \<- paste(dirname,"/",sortproviders\[i\]," AN LIST.xlsx", sep='')
if (grepl(paste(swpatterns, collapse = "|"), sortproviders\[i\]) == FALSE) {
df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
dfformulacol <- as.vector(df$anomalygroup)
df <- cbind(df, df)
XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")
wb <- loadWorkbook(filename = outpath, create = FALSE)
for (j in seq_along(dfformulacol)) {
setCellFormula(wb, "trust list", j+3, 18, dfformulacol[j])
}
for (k in seq_along(dfformulacol)) {
setCellFormula(wb, "trust list", k+3, 45, dfformulacol[k])
}
saveWorkbook(wb)
rm(wb)
} else {
df <- subset(clist[,c(1:18, 20:29)], sortprovider == sortproviders[i])
df <- cbind(df, df)
XLConnect::writeWorksheetToFile(outpath, df, sheet = "trust list", startRow = 4, header = FALSE, styleAction = XLC$"STYLE_ACTION.NONE")
wb <- loadWorkbook(filename = outpath, create = FALSE)
saveWorkbook(wb)
rm(wb)
}
rm(df)
xlcFreeMemory()
}
#####################################

Shiny app: Download data source outside of renderPlot for quicker user manipulation

This is my first shiny app. I would like for the user to be able to update the number of facet columns and the dimensions of downloaded plot. readNWISuv, the function to download data can take a long time if multiple years are queried. Currently, the app downloads the data each time the user wants to change the plot format or plot dimensions. Not sure if I need to use reactiveValues, but I would assume that I want the data to be downloaded and manipulated outside of renderPlot. Thanks!
library(shiny)
library(dataRetrieval)
library(lubridate)
library(tidyverse)
library(plotly)
#flow wrecker
ui <- pageWithSidebar( #fluidPage(
# Application title
titlePanel("Flow Record"),
# Sidebar with a date input
#sidebarLayout
sidebarPanel(
dateRangeInput("daterange", "Date range: (yyyy-mm-dd)",
start = Sys.Date()-10,
min = "1980-10-01"),
textInput("gage", "USGS Gage #", "11532500"),
#actionButton("dload","Download data"),
selectInput("facet_x", "Facet Column #:", 2, choices =1:4),
submitButton("Update View", icon("refresh")),
helpText("When you click the button above, you should see",
"the output below update to reflect the values you",
"entered above:"),
#verbatimTextOutput("value"),
downloadButton('downloadImage', 'Download figure'),
numericInput("fig_x", "Fig. Dim. x:", 10, min = 3, max = 16),
numericInput("fig_y", "Fig. Dim. y:", 10, min = 3, max = 16),
width = 3
),
# Show a plot of the generated WY
mainPanel(
plotlyOutput("WYfacet")
)
)
# Define server draw WY facets
server <- function(input, output) {
parameterCd <- "00060" # discharge
#water year
wtr_yr <- function(dates, start_month=10) {
# Convert dates into POSIXlt
dates.posix = as.POSIXlt(dates)
# Year offset
offset = ifelse(dates.posix$mon >= start_month - 1, 1, 0)
# Water year
adj.year = dates.posix$year + 1900 + offset
# Return the water year
adj.year
}
output$WYfacet <- renderPlotly({
#progress bar
withProgress(readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear,
message = 'Download in progress',
detail = 'This may take a while...', value = 1)
#download
temperatureAndFlow <- readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear
names(temperatureAndFlow)<-c("agc","site","date","WY", "flow","a","tzone")
temperatureAndFlow$commonDate <- as.Date(format(temperatureAndFlow$date, format="2000-%m-%d"))
tf.df<-temperatureAndFlow %>%
filter(WY<=max(WY) & WY>=if_else(month(min(date))<10,min(WY)+1,min(WY)))
tf.df$date.d<-format(tf.df$date, format="%Y-%m-%d")
#mutate commonDate
df4 <- tf.df %>%
mutate(WY=factor(wtr_yr(date.d))) %>%
#seq along dates starting with the beginning of your water year
mutate(commonDate=as.Date(paste0(ifelse(month(date.d) < 10, "2001", "2000"),
"-", month(date.d), "-", day(date.d))), Date=date.d)
#plot
ploty<-ggplot(data = df4,mapping = aes(x = commonDate, y = flow,label=Date, colour = factor(WY))) +
geom_line() +
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log_eng()+
annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE)
ggplotly(ploty, tooltip=c("flow","Date"))
})
#fig dimensions
output$fig_x <- renderText({ input$fig_x })
output$fig_y <- renderText({ input$fig_y })
#facet columns
output$facet_x <- renderText({ input$facet_x })
#download to computer
output$downloadImage <- downloadHandler(
filename = function(){paste("plot",'.png',sep='')},
content = function(file){
ggsave(file,width = input$fig_x,height = input$fig_y, dpi = 600, units = "in", device='png')
print(ggplot(data = df4,mapping = aes(x = commonDate, y = flow, colour = factor(WY))) +
geom_line() +
#geom_point()+
#geom_vline(data = trip,aes(xintercept=commonDate),trip_df,color="black")+
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log_eng()+
annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE))
})
}
# Run the application
shinyApp(ui = ui, server = server)
There are a few changes to make to your sever section to make this work. Primarily:
splitting the creation of the dataframe into a new eventReactive function, dependent on an actionButton.
referring to the function inside the renderPlotly call
Try this:
## Within ui function call ############################################
# submitButton("Update View", icon("refresh")), # line to replace
actionButton(inputId = "update", "Update View", icon("refresh")),
## (if you want to keep a button to control when data is downloaded ##
server <- function(input, output) {
parameterCd <- "00060" # discharge
#water year
wtr_yr <- function(dates, start_month=10) {
# Convert dates into POSIXlt
dates.posix = as.POSIXlt(dates)
# Year offset
offset = ifelse(dates.posix$mon >= start_month - 1, 1, 0)
# Water year
adj.year = dates.posix$year + 1900 + offset
# Return the water year
adj.year
}
# New part here - use `reactive` to make df4 a new thing, which is processed separately. The `eventReactive` function waits till it sees the button pressed.
df4 <- eventReactive(input$update, ignoreNULL = FALSE, {
#progress bar
withProgress(readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear,
message = 'Download in progress',
detail = 'This may take a while...', value = 1)
#download
temperatureAndFlow <- readNWISuv(input$gage, parameterCd, input$daterange[1], input$daterange[2],tz="America/Los_Angeles") %>% addWaterYear
names(temperatureAndFlow)<-c("agc","site","date","WY", "flow","a","tzone")
temperatureAndFlow$commonDate <- as.Date(format(temperatureAndFlow$date, format="2000-%m-%d"))
tf.df<-temperatureAndFlow %>%
filter(WY<=max(WY) & WY>=if_else(month(min(date))<10,min(WY)+1,min(WY)))
tf.df$date.d<-format(tf.df$date, format="%Y-%m-%d")
#mutate commonDate
tf.df %>%
mutate(WY=factor(wtr_yr(date.d))) %>%
#seq along dates starting with the beginning of your water year
mutate(commonDate=as.Date(paste0(ifelse(month(date.d) < 10, "2001", "2000"),
"-", month(date.d), "-", day(date.d))), Date=date.d)
})
output$WYfacet <- renderPlotly({
# req will pause plot loading till new data downloaded above, but changes to display will render without new download
req(df4())
#plot
ploty<-ggplot(data = df4(), # Put brackets here to refer to df4 as a reactive input!!!
mapping = aes(x = commonDate, y = flow, label=Date, colour = factor(WY))) +
geom_line() +
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log10()+
# annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE)
ggplotly(ploty, tooltip=c("flow","Date"))
})
#fig dimensions
output$fig_x <- renderText({ input$fig_x })
output$fig_y <- renderText({ input$fig_y })
#facet columns
output$facet_x <- renderText({ input$facet_x })
#download to computer
output$downloadImage <- downloadHandler(
filename = function(){paste("plot",'.png',sep='')},
content = function(file){
ggsave(file,width = input$fig_x,height = input$fig_y, dpi = 600, units = "in", device='png')
print(ggplot(data = df4() ,mapping = aes(x = commonDate, y = flow, colour = factor(WY))) +
geom_line() +
#geom_point()+
#geom_vline(data = trip,aes(xintercept=commonDate),trip_df,color="black")+
labs(x = " ", y = "Discharge (cfs)") +
facet_wrap(facets = ~WY,ncol=as.integer(input$facet_x)) +
scale_y_log10()+
annotation_logticks(sides = "l")+
theme_bw()+
theme(panel.grid.minor.x = element_blank())+
scale_x_date(labels = function(x) format(x, "%b"),date_breaks = "1 months")+
guides(colour=FALSE))
})
}

Error in active reactive context - How to fix?

Hey I am trying to build a shiny app for the purpose of calculating per cent chance of defaulting and I thought I fixed all my issues until I hit
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.)
but whenever I try to build something reactive I get
Error in RET#get_where(newdata = newdata, mincriterion = mincriterion) :
object 'loanfilev3' not found
I've looked over stackoverflow and tutorials and none seem to really help
Here is my UI and Server code for the first error, if someone could please highlight my issue that would be greatly appreciated.
UI:
library(shiny)
shinyUI(fluidPage(
titlePanel("Tabsets"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select the random distribution type ----
numericInput("loan_amnt",
"Loan Amount:",
value = 5000,
min = 0,
max = NA),
numericInput("int_rate",
"Interest Rate:",
value = 10.5,
min = 0,
max = NA),
selectInput("term",
"Loan Term:",
c("36 months" = " 36 months",
"60 months" = " 60 months")),
numericInput("installment",
"Installment:",
value = 100,
min = 0,
max = NA),
textInput("grade", "Grade:", "B"),
textInput("emp_length", "Employment Length:", "5 years"),
numericInput("annual_inc",
"Annual Income:",
value = 40000,
min = 0,
max = NA),
numericInput("dti",
"Debt to Income Ratio:",
value = 5.4,
min = NA,
max = NA),
textInput("sub_grade", "SubGrade:", "B2"),
textInput("verification_status", "Verification Status:", "Verified"),
textInput("home_ownership", "Home Ownership:", "RENT"),
radioButtons("pymnt_plan", "Payment Plan:",
c("Yes" = "y",
"No" = "n"))
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Decision Tree", verbatimTextOutput("ct")),
tabPanel("Generlized Linear Model", verbatimTextOutput("dl")),
tabPanel("K-Nearest Neighbour", verbatimTextOutput("kn"))
)
)
)
)
)
Server:
library(shiny)
library(pscl)
library(ROCR)
library(plyr)
library(dplyr)
library(ggplot2)
library(pROC)
library(caret)
library(e1071)
library(RMySQL)
library(reshape2)
USER <- 'inft216'
PASSWORD <- 'rosemary'
HOST <- 'bruce3.dc.bond.edu.au'
DBNAME <- 'inft216'
db <- dbConnect(MySQL(), user = USER, password = PASSWORD, host = HOST, dbname = DBNAME)
loanfile <- dbGetQuery(db, statement = "select * from lendingClub;")
dbDisconnect(db)
library(party)
colnames(loanfile) = tolower(colnames(loanfile))
bad_indicators = c("Charged Off",
"Default",
"Does not meet the credit policy. Status:Charged Off",
"Default Receiver",
"Late (16-30 days)",
"Late (31-120 days)")
loanfile$default = ifelse(loanfile$loan_status %in% bad_indicators, 1,
ifelse(loanfile$loan_status=="", NA, 0))
loanfile$loan_status = as.factor(loanfile$default)
loanfilev2 = dplyr::select(.data = loanfile,loan_status,loan_amnt,int_rate,term,installment,grade,emp_length,annual_inc,dti,sub_grade,verification_status,home_ownership,pymnt_plan)
loanfilev2$grade = as.factor(loanfilev2$grade)
loanfilev2$sub_grade <- as.factor(loanfilev2$sub_grade)
loanfilev2$term <- as.factor(loanfilev2$term)
loanfilev2$emp_length <- as.factor(loanfilev2$emp_length)
loanfilev2$verification_status <- as.factor(loanfilev2$verification_status)
loanfilev2$home_ownership <- as.factor(loanfilev2$home_ownership)
loanfilev2$pymnt_plan <- as.factor(loanfilev2$pymnt_plan)
loanfilev2$loan_status <- as.factor(loanfilev2$loan_status)
loanfilev2$grade <- as.numeric(loanfilev2$grade)
loanfilev2$sub_grade <- as.numeric(loanfilev2$sub_grade)
loanfilev2$term <- as.numeric(loanfilev2$term)
loanfilev2$emp_length <- as.numeric(loanfilev2$emp_length)
loanfilev2$verification_status <- as.numeric(loanfilev2$verification_status)
loanfilev2 <- loanfilev2[complete.cases(loanfilev2),]
set.seed(69)
train_index <- sample(seq_len(nrow(loanfilev2)), size = 5000)
TrainData<- loanfilev2[train_index, ]
ct = ctree(loan_status ~ ., data = TrainData)
dl <- glm(formula = loan_status ~ .,data = loanfilev2, family = binomial)
kn <- train(form = loan_status ~.,data = TrainData, method = 'knn')
shinyServer(function(input, output) {
loan_status <- c(0)
loan_amnt <- input$loan_amnt
int_rate <- input$int_rate
term <- input$term
installment <- input$installment
grade <- input$grade
emp_length <- input$emp_length
annual_inc <- input$annual_inc
dti <- input$dti
sub_grade <- input$sub_grade
verification_status <- input$verification_status
home_ownership <- input$home_ownership
pymnt_plan <- input$pymnt_plan
temp2 <- cbind(loan_status, loan_amnt, int_rate, term, installment, grade, emp_length, annual_inc, dti, sub_grade, verification_status, home_ownership, pymnt_plan)
loanfilev3 = dplyr::select(.data = loanfile,loan_status,loan_amnt,int_rate,term,installment,grade,emp_length,annual_inc,dti,sub_grade,verification_status,home_ownership,pymnt_plan)
loanfilev3 = rbind(loanfilev3, temp2, deparse.level = 0)
loanfilev3$grade = as.factor(loanfilev3$grade)
loanfilev3$sub_grade <- as.factor(loanfilev3$sub_grade)
loanfilev3$term <- as.factor(loanfilev3$term)
loanfilev3$emp_length <- as.factor(loanfilev3$emp_length)
loanfilev3$verification_status <- as.factor(loanfilev3$verification_status)
loanfilev3$home_ownership <- as.factor(loanfilev3$home_ownership)
loanfilev3$pymnt_plan <- as.factor(loanfilev3$pymnt_plan)
loanfilev3$loan_status <- as.factor(loanfilev3$loan_status)
loanfilev3$grade <- as.numeric(loanfilev3$grade)
loanfilev3$sub_grade <- as.numeric(loanfilev3$sub_grade)
loanfilev3$term <- as.numeric(loanfilev2$term)
loanfilev3$emp_length <- as.numeric(loanfilev3$emp_length)
loanfilev3$verification_status <- as.numeric(loanfilev3$verification_status)
loanfilev3 <- loanfilev3[complete.cases(loanfilev3),]
prediction1 = c(predict(object = ct, newdata = loanfilev3[886508], type = "prob"))
output$ct <- renderPrint({
as.data.frame(prediction1)[2,]*100
})
})
All input bindings (input$whatever) need to be used in reactive context for example: inside reactive() or observe or renderXXX etc. In your case you are doing stuff like loan_amnt <- input$loan_amnt outside of reactive context and that's what the error is about. See my update below. I have added your prediction model to an eventReactive that is triggered by some action button input$predict.
# add this button somewhere in your ui.R -
actionButton("predict", "Predict!")
update to server.R -
shinyServer(function(input, output) {
prediction <- eventReactive(input$predict, {
loan_status <- c(0)
loan_amnt <- input$loan_amnt
int_rate <- input$int_rate
term <- input$term
installment <- input$installment
grade <- input$grade
emp_length <- input$emp_length
annual_inc <- input$annual_inc
dti <- input$dti
sub_grade <- input$sub_grade
verification_status <- input$verification_status
home_ownership <- input$home_ownership
pymnt_plan <- input$pymnt_plan
temp2 <- cbind(loan_status, loan_amnt, int_rate, term, installment, grade, emp_length, annual_inc, dti, sub_grade, verification_status, home_ownership, pymnt_plan)
loanfilev3 = dplyr::select(.data = loanfile,loan_status,loan_amnt,int_rate,term,installment,grade,emp_length,annual_inc,dti,sub_grade,verification_status,home_ownership,pymnt_plan)
loanfilev3 = rbind(loanfilev3, temp2, deparse.level = 0)
loanfilev3$grade = as.factor(loanfilev3$grade)
loanfilev3$sub_grade <- as.factor(loanfilev3$sub_grade)
loanfilev3$term <- as.factor(loanfilev3$term)
loanfilev3$emp_length <- as.factor(loanfilev3$emp_length)
loanfilev3$verification_status <- as.factor(loanfilev3$verification_status)
loanfilev3$home_ownership <- as.factor(loanfilev3$home_ownership)
loanfilev3$pymnt_plan <- as.factor(loanfilev3$pymnt_plan)
loanfilev3$loan_status <- as.factor(loanfilev3$loan_status)
loanfilev3$grade <- as.numeric(loanfilev3$grade)
loanfilev3$sub_grade <- as.numeric(loanfilev3$sub_grade)
loanfilev3$term <- as.numeric(loanfilev2$term)
loanfilev3$emp_length <- as.numeric(loanfilev3$emp_length)
loanfilev3$verification_status <- as.numeric(loanfilev3$verification_status)
loanfilev3 <- loanfilev3[complete.cases(loanfilev3),]
predict(object = ct, newdata = loanfilev3[886508], type = "prob"))
})
output$ct <- renderPrint({
as.data.frame(prediction())[2,]*100
})
})

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

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

Knitr - Error in usemethod("round_any"): no applicable method for round_any applied

I'm trying to output some of my code results in knitr. Now the strange thing is, the code generates the error in the title. But running round_any() seperately and outputting it in knitr is fine.
knitr code
```{r, echo = FALSE, message=FALSE, warning=FALSE}
source("BooliQuery.R")
BooliQuery()
```
My code
library(digest)
library(stringi)
library(jsonlite)
library(plyr)
BooliQuery <- function(area = "stockholm", type="lägenhet", sincesold = "", FUN = "", limit = 250, offset = 0, mode = 1) {
#raw data fetch + adjust.
lOriginal <- GETAPI(area, type, sincesold, FUN, limit, offset)
lOriginal$AreaSize <- round_any(lOriginal$livingArea, 10, floor)
lOriginal$PriceDiff <- lOriginal$soldPrice - lOriginal$listPrice
#Create frame overview
Overview.Return <- Frame.Overview(lOriginal)
#Mode - return selector
ifelse( mode == 1, return (Overview.Return), return (lOriginal) )
}
Frame.Overview <- function(lOriginal) {
#Aggregate mean
listPrice <- aggregate(lOriginal, list(lOriginal$AreaSize), FUN = mean, na.rm = TRUE)
colnames(listPrice)[1] <- "SegGroup"
listPrice <- listPrice[, c("SegGroup", "listPrice", "soldPrice", "PriceDiff", "rent", "livingArea", "constructionYear") ]
#Perform Rounding
listPrice[, c(2:5)] <- round(listPrice[,c(2:5)], digits = 0)
listPrice[, 6] <- round(listPrice[, 6], digits = 1)
listPrice[, 7] <- signif(listPrice[,7], digits = 4)
return(listPrice)
}
GETAPI <- function(area = "stockholm", type="lägenhet", sincesold = "", FUN = "", limit = 250, offset = 0) {
#ID Info
key <- "PRIVATE KEY"
caller.ID <- "USERNAME"
#//
unix.timestamp <- as.integer( as.POSIXct(Sys.time()) )
random.string <- stri_rand_strings( n = 1, length = 16)
#Sha1-Hash: CallerID + time + key + unique, 40-char hexadecimal
hash.string <- paste0(caller.ID, unix.timestamp, key, random.string)
hash.sha1 <- digest(hash.string,"sha1",serialize=FALSE)
#Create URL
api.string <- "https://api.booli.se/sold?q="
url.string <- paste0(api.string, area, "&objectType=" , type , "&minSoldDate=", sincesold, FUN, "&limit=", limit, "&offset=", offset,"&callerId=", caller.ID, "&time=" ,
unix.timestamp, "&unique=", random.string, "&hash=", hash.sha1)
#Parse JSON
parsed.JSON <- fromJSON(txt = url.string)
return(parsed.JSON$sold)
}
Running the code seperately in console is fine. So what could be wrong?

Resources