I am having some trouble with creating plots on eventReactive. I have a source code for inside event reactive, and I am trying to make multiple plots. I am a little unsure how to make multiple plots, so I tried to make one into a plot. However, I am still having trouble with this.
My ui and server are
library(shiny)
library(lpSolve)
ui <- fluidPage(
mainPanel(
tabsetPanel(
tabPanel("Information required for the model",
sliderInput("Reservoirs", label = h3("Total Number of Reservoirs"),
min = 1, max = 25,
value = 10),
sliderInput("Municipalities", label = h3("Total Number of Municipalities Served by the Reservoirs"),
min = 1, max = 150,
value = 15),
sliderInput("Time", label = h3("Total Number of Months for Future Decision"),
min = 0, max = 60,
value = 0)
),
tabPanel("Summary of csv files",
actionButton("Run_Model", "Run Model")),
tabPanel("Results",
plotOutput("plot_ipsita"),
img(outfile)
)
)))
server <- function(input, output) {
running_code<-eventReactive(input$Run_Model, {
source("Source_code.R", local=TRUE)
outfile <- tempfile(fileext = '.png')
png(outfile,width=30,height=nR*3,units = "in",res=200)
par(mfrow=c(ceiling(nR)/2, 2))
for (i in 1:nR){
hist(abcd[i,1,1])
}
dev.off()
plot((colSums(abcd[1,,])),type="l",ylab="Withdrawal [mio m3]",xlab = "months",col=1,lwd=3,lty=1)
abline(h=130, col = 2,lwd=3,lty=3)
abline(h=205, col=3, lwd=3,lty=4)
legend("topleft", c("","All Reservoirs","Import","Failure"), col = c(0,1,2,3),pt.cex=0.5,lty=1:4,lwd=3, cex=0.75,bty="n")
title(paste0("Withdrawals from reservoirs and imports and failure for % initial storage" ), cex.main=1)
})
output$plot_ipsita <- renderPlot({
running_code()
})
}
shinyApp(ui = ui, server = server)
And my source code is
nR<-input$Reservoirs
nM<-input$Municipalities
nT<-input$Time
abcd<-array(data=0, c(nR,nM,nT))
for (i in 1:nR){
abcd[i,,]<-(1+i)*55
}
My actual code is a lot more complicated, so I tried to simplify it to test with this one, and it does not seem happy. Nothing is running. However, if I try to run it as a regular R code, I am able to get all the results.
Please help!!!
The mistake in your code is in your ui where your sliderInput Time has a default value 0. This causes the following loop to fail not assigning any value to array abcd:
for (i in 1:nR){
abcd[i,,]<-(1+i)*55
}
Hence, colSums(abcd[1,,]) dos not have the value due to which it fails.
If you change the sliderInput("Time", label = h3("Total Number of Months for Future Decision"), min = 0, max = 60, value = 0) to sliderInput("Time", label = h3("Total Number of Months for Future Decision"), min = 0, max = 60, value = 2) your code creates a graph as follows:
Hope it helps!
Related
Intro:
I have a list of 40 variables that each has 2000 entries, I am working in R Shiny in order to try automatically divide the data into 3 bins based the value at 1/3 of the data and 2/3 of the data.
Each variable has a range between -10 and 10.
UI code below:
selectInput("variable","Select your variable",choices = sort(colnames(train))),noUiSliderInput(inputId = "bins", label = "Choose bin width", min = -10, max = 10, value = c(NULL,NULL), orientation = "horizontal", margin = 1, width = 10000, color = "#68228B")
Server code:
ordered_data <- reactive({
sort_test <- c(joined_adw[,input$variable])
sort_test <- as.numeric(unlist(sort_test))
sort_test <- sort(sort_test)
})
eventReactive(
input$variable,{
updateNoUiSliderInput(session = session, inputId = "bins", value = c(ordered_data()[667], test()[1334]))
})
}
I know that there are other ways of doing this, but I need the slider in the report sheet.
Any help would be massively appreciated, as I have been trying to do this for a while, and each time I try it, the slider disappears when I use an update call.
This is the code I have on my server file:
shinyServer(function(input, output) {
output$P = renderText(input$Slider1)
output$n = renderText(input$numeric1)
output$r = renderText(input$numeric2/100)
futureValue <- reactive({
principal <- output$P
numberOfPeriods <- output$n
rate <- output$r
fvalue <- principal*(((1+rate)^numberOfPeriods-1)/rate)
return(fvalue)
})
output$fv <- renderText(futureValue)
})
Code for main panel on UI File:
sidebarPanel(
h4("Select Monthly Investment Amount:"),
sliderInput("Slider1","Select Monthly Investment Amount:", 100, 1000,
100),
numericInput("numeric1", "Select Number of Payments:", value = 12, min
= 6, max = 60, step = 1),
numericInput("numeric2", "Select Interest Rate Percentage:", value =
3.0, min = 0.1, max = 5.0, step = 0.1)
mainPanel
(
h4("Monthly Investment Amount:"),
textOutput("P"),
h4("Number of Periods:"),
textOutput("n"),
h4("Interest Rate:"),
textOutput("r"),
h4("Under the given circumstances, the future value of your
investment is:"),
textOutput("fv")
)
Everything works except for the last part where I'm performing the calculations for future value. Would anyone be able to tell me what I'm doing wrong?
Hi reactivs are functions not variables
output$fv <- renderText(futureValue() )
and change the reactive function like this
futureValue <- reactive({
principal <- input$Slider1
numberOfPeriods <- input$numeric1
rate <- input$numric2
fvalue <-principal*(((1+rate)^numberOfPeriods-1)/rate)
return(fvalue) })
should solve it.
Hope this helps!
I am trying to make a Shiny app to do calculations as in [this pape
There are 3 sorts of calculation,called "calcprior", "calcpval" and "calcFPR".
Which calculation is to be done is chosen by radioButton. Each calculation requires different inputs. The inputs are placed in conditionalPanels. The correct names appear in thec onditionalPanel, but the numerical values aren't passed to the server, e.g. input$pval does not have the value entered in the numericInput in the conditional panel.
In contrast the value of nsamp, needed for all 3 calculations, is passed correctly to the server.
I'm a beginner at Shiny, so I hope that someone can explain what's going wrong. Not being able to see the values of variables makes debugging a million times harder than in regular R.
sidebarLayout(
sidebarPanel(
radioButtons("calctype", "Choose calculation:",selected = "calcFPR",
choices = c(
"prior (for given FPR and P val)" = "calcprior",
"P value (for given FPR and prior)" = "calcpval",
"FPR (for given P value and prior)" = "calcFPR")),
conditionalPanel(
condition = "input.calctype == 'calcprior'",
numericInput("pval", label = h5("observed P value"), value = 0.05, min
= 0, max = 1),
numericInput("FPR", label = h5("false positive risk"), value = 0.05,
min = 0, max = 1)
),
conditionalPanel(
condition = "input.calctype == 'calcpval'",
numericInput("FPR", label = h5("false positive risk"), value = 0.05,
min = 0, max = 1),
numericInput("prior", label = h5("prior probability of real effect"),
value = 0.5, min = 0, max = 1)
),
conditionalPanel(
condition = "input.calctype == 'calcFPR'",
numericInput("pval",label = h5("observed P value"),value = 0.05, min =
0, max = 1),
numericInput("prior", label = h5("prior probability of real effect"),
value = 0.5, min = 0., max = 1.)
),
inputPanel(
numericInput("nsamp",label = h5("Number in each sample"), step = 1,
value = 16, min = 2)
),
mainPanel(
(I also need to work out how to use the calctype to direct the server to the appropriate block of R code.)
Here is a working example for you:
library(shiny)
ui <- fluidPage(
titlePanel("|Species Table"),
sidebarLayout(
sidebarPanel(
radioButtons("calctype", "Choose calculation:",selected = "calcFPR",
choices = c(
"prior (for given FPR and P val)" = "calcprior",
"P value (for given FPR and prior)" = "calcpval",
"FPR (for given P value and prior)" = "calcFPR")),
uiOutput("test1"),
uiOutput("test2"),
inputPanel(
numericInput("nsamp",label = h5("Number in each sample"), step = 1,
value = 16, min = 2)
)),
mainPanel(textOutput("text1"),
textOutput("text2"))
))
server <- function(input, output) {
test <- reactive({
if(input$calctype == 'calcprior'){
label1 <- paste("observed P value")
label2 <- paste("false positive risk")
}else if(input$calctype == 'calcpval'){
label1 <- paste("false positive risk")
label2 <- paste("prior probability of real effect")
}else{
label1 <- paste("observed P value")
label2 <- paste("prior probability of real effect")
}
list(label1 = label1, label2 = label2)
})
output$test1 <- renderUI({
numericInput("test1", label = h5(test()$label1), value = 0.05, min = 0, max = 1)
})
output$test2 <- renderUI({
numericInput("test2", label = h5(test()$label2), value = 0.05, min = 0, max = 1)
})
output$text1 <- renderText({
input$test1
})
output$text2 <- renderText({
input$test2
})
}
shinyApp(ui = ui, server = server)
you do not need so many conditionalPanels, i have noticed in your code that the only thing that changes is the label of numericInput according to choosen calculation type. Therefore in this case i have used if...else... statement in the server to change the label of two `numericInputs (test1 and test2) with choosen calculation type.
Furthermore i have printed out the output of the numericInput `s (text1 and text2) to show you that the user input is acctually passed to server and can be further used in the calculations.
I'm trying to incorporate three plots in shiny, all of which use the d3 library. On placing them in different tabPanels(or the same one for that matter), I see only one or two plots, and they do not react properly. One of the plots is pulled from 'pp.html' and is based on d3.v3.min.js library. Second plot is pulled from 'australian.html' and it uses d3.v4.js library. The third plot is created using scatterD3 library of R.
A minimum working example is given below:
ui.R
shinyUI(bootstrapPage(
navbarPage("You Got Served!", id = "page",
tabPanel("Overall Analysis", value = "panel1",
h2(textOutput("title")),
scatterD3Output("scatter", width = "1500", height = "700"),
br()),
tabPanel("Parallel Coordinate", value = "panel2",
fluidRow(
column(2,
uiOutput("pc", width = 700, height = 600),
br())
)),
tabPanel("Sunburst", value= "panel3",
suppressDependencies("d3.v3.min.js"),
uiOutput("gs"),
br(),
hr())
)))
server.R
shinyServer(function(input, output, session) {
session$onSessionEnded({stopApp})
output$scatter <- renderScatterD3({
dat <- mydata %>%
mutate(FirstServePercent = (w_1stIn/w_svpt) * 100, MatchDuration =
minutes, Hand = winner_hand) %>%
select(FirstServePercent, MatchDuration, Hand, Surface = surface,
Tournament = tourney_name)
s1 <- scatterD3(data = dat, y = FirstServePercent, x = MatchDuration,
col_var = Surface, symbol_var = Hand, point_size = 70, labels_size = 30,
xlab = "Match Duration (in minutes)", ylab = "First Serve %", axes_font_size
= "15px", legend_font_size = '20', point_opacity = 0.5, hover_size = 1.8,
hover_opacity = 1, transition = TRUE)
s1
})
output$gs <- renderUI({
return(htmlTemplate("australian.html"))})
output$pc <- renderUI({
return(htmlTemplate("pp.html"))})
})
I tried to find examples relating to the usage of suppressDependencies() function in R, but was not able to find any working ones. I want to know where exactly should I use that function to render the three charts correctly, with their relevant interactions. If the solution involves using a functionality other than suppressDependencies, I'll really appreciate that too.
A part of the dataset mydata looks something like this:
You can use iframes in your renderUi to avoid dependencies issues:
plot is pulled from 'australian.html' and it uses d3.v4.js library. The third plot is created using scatterD3 library of R.
output$gs <- renderUI({
tags$iframe(src='australian.html',width="100%",frameBorder="0",height="500px")
})
output$pc <- renderUI({
tags$iframe(src='pp.html',width="100%",frameBorder="0",height="500px")
})
I'm using shiny::updateSliderInput to update the label of a slider. I would like the label for the slider to render with the Greek character xi (ξ) and a subscript. The subscript is target of the updateSliderInput call.
I've been successful generating the label without the updateSliderInput call, but correctly using the withMathJax() call for the label update has not worked as well as I would prefer.
A reproducible example of a shiny app for this issue is:
library(shiny)
shinyApp(ui = shinyUI(fluidPage(sliderInput("order", withMathJax("Order, \\(k\\)"), min = 3, max = 7, value = 4, step = 1),
sliderInput("iknots", "iKnots", min = 0, max = 10, value = 5, step = 1),
sliderInput("xi1", withMathJax(), min = 0, max = 10, value = 1, step = 0.1))),
server = shinyServer(function(input, output, clientData, session) {
observe({
k <- as.integer(input$order)
l <- as.integer(input$iknots)
updateSliderInput(session, "xi1", label = paste0("\\(\\xi_{", k + l, "}\\)"))
})
}))
Upon initial loading of the app in browser we have a the desirable label, the ξ9 is correct.
After adjusting either of the first two sliders, the label for the third slider does not render as expected.
I've tried using withMathJax in label argument of updateSliderInput but have had undesirable labels. Changing the updateSliderInput line in the above to
updateSliderInput(session, "xi1", label = withMathJax(paste0("\\(\\xi_{", k + l, "}\\)")))
and setting the sliderInput to have the either label = withMathJax() or label = "" results in the initial label of
and updated label of
How can the subscript on the ξ be correctly updated in the slider label?
You might need to use renderUI and uiOutput to create the last slider otherwise the javascript used to display the MathJax is not called when you update the label.
You could do:
library(shiny)
shinyApp(ui = shinyUI(fluidPage(sliderInput("order", withMathJax("Order, \\(k\\)"), min = 3, max = 7, value = 4, step = 1),
sliderInput("iknots", "iKnots", min = 0, max = 10, value = 5, step = 1),
uiOutput("lastSlider"))),
server = shinyServer(function(input, output, clientData, session) {
output$lastSlider<- renderUI({
k <- as.integer(input$order)
l <- as.integer(input$iknots)
sliderInput("xi1",label = withMathJax(paste0("\\(\\xi_{", k + l, "}\\)")), min = 0, max = 10, step = 0.1,value=input$xi1)
})
}))