How to calculate an mathematic expresion reciving values from sliders - r

I am new in Shiny and i am trying to learn. My issue is that i want to calculate an mathematic expresion by giving a value from slider and in the end to show the result. Until now i have made the following code but it is wrong. Could you please guide me.
Thanks in advance
library(shiny)
library(shinythemes)
# Define UI for slider demo app ----
ui <- fluidPage(
#Navbar structure for UI
navbarPage("SAR Model", theme = shinytheme("united"),
tabPanel("Toblers Function", fluid = TRUE),
# App title ----
titlePanel("Toblers Fuction"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar to demonstrate various slider options ----
sidebarPanel(
# Input: Slope interval with step value ----
sliderInput("slope", "Slope:",
min = -0.60, max = 0.50,
value = 0.0, step = 0.01),
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Table summarizing the values entered ----
tableOutput("values")
)
)
)
)
server <- function(input, output, session) {
# Reactive expression to create data frame off input value ----
sliderValues <- reactive({
data.frame(
Name = c("Slope"),
Value = as.character(c(input$slope)),
stringsAsFactors = FALSE)
})
Value$toblers <- 6*exp(-3.5*input$slope)
# Show the values in an HTML table ----
output$values <- renderTable({
sliderValues()
})
output$tobler <-renderText({value$toblers})
}
shinyApp(ui = ui, server = server)

You use input$slope outside of a reactive context which is not allowed. Define a reactive for your calculation of toblers and then display this, like:
toblers <- reactive({
6*exp(-3.5*input$slope)
})
output$tobler <-renderText({toblers()})

Ok i made some changes but does not show the result.
Here is the code
library(shiny)
library(shinythemes)
# Define UI for slider demo app ----
ui <- fluidPage(
#Navbar structure for UI
navbarPage("SAR Model", theme = shinytheme("united"),
tabPanel("Toblers Function", fluid = TRUE),
# App title ----
titlePanel("Toblers Fuction"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar to demonstrate various slider options ----
sidebarPanel(
# Input: Slope interval with step value ----
sliderInput("slope", "Slope:",
min = -0.60, max = 0.50,
value = 0.0, step = 0.01)),
# Main panel for displaying outputs ----
mainPanel(
# Output: Table summarizing the values entered ----
tableOutput("values"),
)
)
)
)
server <- function(input, output, session) {
# Reactive expression to create data frame off input value ----
sliderValues <- reactive({
data.frame(
Name = c("Slope"),
Value = as.character(c(input$slope)),
stringsAsFactors = TRUE)
})
# Show the values in an HTML table ----
output$values <- renderTable({
sliderValues()
})
output$slope <- renderText({
paste0("The speed is ", 6*exp(-3.5*input$slope),"Km/h")
})
}
shinyApp(ui = ui, server = server)

I found a solution but know does not appear the table with the value from slider.
Any opinion why?
here is the code
library(shiny)
library(shinythemes)
# Define UI for slider demo app ----
ui <- fluidPage(
#Navbar structure for UI
navbarPage("SAR Model", theme = shinytheme("united"),
tabPanel("Toblers Function", fluid = TRUE),
# App title ----
titlePanel("Toblers Fuction"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar to demonstrate various slider options ----
sidebarPanel(
# Input: Slope interval with step value ----
sliderInput("slope", "Slope:",
min = -0.60, max = 0.50,
value = 0.0, step = 0.01)),
# Main panel for displaying outputs ----
mainPanel(
# Output: Table summarizing the values entered ----
tableOutput("Values"),
tableOutput("slope")
)
)
)
)
server <- function(input, output, session) {
# Reactive expression to create data frame off input value ----
sliderValues <- reactive({
data.frame(
Name = c("Slope"),
Value = as.character(c(input$slope)),
stringsAsFactors = TRUE)
})
# Show the values in an HTML table ----
output$values <- renderTable({
sliderValues()
})
output$slope <- renderText({
paste0("The speed is ", 6*exp(-3.5*abs(input$slope+0.05)),"Km/h")
})
}
shinyApp(ui = ui, server = server)

Related

Split one Shiny app into two when using iframes?

I have a Shiny app where the user makes a data selection and results for this selection are then visualized.
The following toy example illustrates the logic described above. The user chooses input$obs which specifies the vector faithful$waiting[1:input$obs] and we then plot a histogram for this vector:
library(shiny)
ui <- fluidPage(
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of observations ----
sliderInput(inputId = "obs",
label = "Number of observations:",
min = 1,
max = length(faithful$waiting),
value = 30)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
plotOutput(outputId = "distPlot")
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
output$distPlot <- renderPlot({
hist(faithful$waiting[1:input$obs], main = "", xlab = "")
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)
I run this app using Shiny Server and show it on my website through an iframe.
My question is: How do I split the slider and the histogram so I can have them in two separate iframes on my website?

Hello shiny app gives me error in reactive expression

Hello i am trying to reproduce an example of shiny apps of RStudio in this link:
https://shiny.rstudio.com/articles/tabsets.html
The shinyapp gives error with the d() reactive expression, and i try to change the expression but gives me error:
The code is:
library(shiny)
Define UI for random distribution app ----
ui <- fluidPage(
# App title ----
titlePanel("Tabsets"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select the random distribution type ----
radioButtons("dist", "Distribution type:",
c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")),
# br() element to introduce extra vertical spacing ----
br(),
# Input: Slider for the number of observations to generate ----
sliderInput("n",
"Number of observations:",
value = 500,
min = 1,
max = 1000)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)
)
)
)
Define server logic for random distribution app ----
server <- function(input, output) {
# Reactive expression to generate the requested distribution ----
# This is called whenever the inputs change. The output functions
# defined below then use the value computed from this expression
d <- reactive({
dist <- switch(input$dist,
norm = rnorm,
unif = runif,
lnorm = rlnorm,
exp = rexp,
rnorm)
dist(input$n)
})
# Generate a plot of the data ----
# Also uses the inputs to build the plot label. Note that the
# dependencies on the inputs and the data reactive expression are
# both tracked, and all expressions are called in the sequence
# implied by the dependency graph.
output$plot <- renderPlot({
dist <- input$dist
n <- input$n
hist(d(),
main = paste("r", dist, "(", n, ")", sep = ""),
col = "#75AADB", border = "white")
})
# Generate a summary of the data ----
output$summary <- renderPrint({
summary(d())
})
# Generate an HTML table view of the data ----
output$table <- renderTable({
d()
})
}
Create Shiny app ----
shinyApp(ui, server)
The error when i run the app is:
Warning: Error in dist: invalid arguments
reactive:d [C:\Users\pruebas\Documents\Shiny_examples\tabs/app.R#63]
Can someone help i am trying to learn my first apps looking in articles at RStudio, but this one is wrong, and it is supposed to be done to teach people like me. I also dearch in github but i found the same code.Thank you.
Your app works fine.
Are you saving it as two separate files, i.e, ui.r and server.r, or a single file, i.e. app.r?
Your code is set up for it being saved as two separate files, but the error looks like you might have saved it as a single file.
Try saving it as two files:
ui.r
ui <- fluidPage(
# App title ----
titlePanel("Tabsets"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select the random distribution type ----
radioButtons("dist", "Distribution type:",
c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")),
# br() element to introduce extra vertical spacing ----
br(),
# Input: Slider for the number of observations to generate ----
sliderInput("n",
"Number of observations:",
value = 500,
min = 1,
max = 1000)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)
)
)
)
server.r
server <- function(input, output) {
# Reactive expression to generate the requested distribution ----
# This is called whenever the inputs change. The output functions
# defined below then use the value computed from this expression
d <- reactive({
dist <- switch(input$dist,
norm = rnorm,
unif = runif,
lnorm = rlnorm,
exp = rexp,
rnorm)
dist(input$n)
})
# Generate a plot of the data ----
# Also uses the inputs to build the plot label. Note that the
# dependencies on the inputs and the data reactive expression are
# both tracked, and all expressions are called in the sequence
# implied by the dependency graph.
output$plot <- renderPlot({
dist <- input$dist
n <- input$n
hist(d(),
main = paste("r", dist, "(", n, ")", sep = ""),
col = "#75AADB", border = "white")
})
# Generate a summary of the data ----
output$summary <- renderPrint({
summary(d())
})
# Generate an HTML table view of the data ----
output$table <- renderTable({
d()
})
}

How to align elements in a tabset using fluidRow

I want to have my plot next to summary statistics inside of a tabPanel. I am trying to use fluidRow to do this but I cant seem to get the elements to align side by side. What am I doing wrong?
library(shiny)
# Define UI for random distribution app ----
ui <- fluidPage(
# App title ----
titlePanel("Tabsets"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select the random distribution type ----
radioButtons("dist", "Distribution type:",
c("Normal" = "norm",
"Uniform" = "unif",
"Log-normal" = "lnorm",
"Exponential" = "exp")),
# br() element to introduce extra vertical spacing ----
br(),
# Input: Slider for the number of observations to generate ----
sliderInput("n",
"Number of observations:",
value = 500,
min = 1,
max = 1000)
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Plot",
fluidRow(
column(6,wellPanel(plotOutput("plot"))),
column(6,wellPanel(verbatimTextOutput("summary")))
)
)
)
# Define server logic for random distribution app ----
server <- function(input, output) {
# Reactive expression to generate the requested distribution ----
# This is called whenever the inputs change. The output functions
# defined below then use the value computed from this expression
d <- reactive({
dist <- switch(input$dist,
norm = rnorm,
unif = runif,
lnorm = rlnorm,
exp = rexp,
rnorm)
dist(input$n)
})
# Generate a plot of the data ----
output$plot <- renderPlot({
dist <- input$dist
n <- input$n
hist(d(),
main = paste("r", dist, "(", n, ")", sep = ""),
col = "#75AADB", border = "white")
})
# Generate a summary of the data ----
output$summary <- renderPrint({
summary(d())
})
}
# Create Shiny app ----
shinyApp(ui, server)
I have tried your Code...output is below picture...

using drop down bottom in shiny to loaed files from a folder

I am using shiny to upload different data files from a certain folder and plot a histogram based on a certain column. The name of each file looks like "30092017ARB.csv" (date + ARB.csv).
The code loops over all file names in the data-folder and print the name of files in a drop-down bottom. After selecting the name of file it should be uploaded and plot a histogram of the mw-column (the name of column is "mw). My GUI looks as follows:
library("shiny")
dataset <- list.files("C:/R_myfirstT/data", pattern=".*.csv$")
# Define UI for dataset viewer app ----
ui <- fluidPage(
# App title ----
titlePanel("Data plot"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Selector for choosing dataset ----
selectInput(inputId = "date",
label = "Choose a date:",
choices = dataset)
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot")
)
)
)
and the server
# Define server ----
dataset <- list.files("C:/R_myfirstT/data", pattern=".*.csv$")
dat.name<-paste("C:/R_myfirstT/data/",dataset,sep = "")
server <- function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
for (i in 1:length(dataset)){
toString(dataset[i])=read.csv(file=dat.name[i], header=TRUE, sep=";")
}
)
output$plot <- renderPlot({
hist(dataset.mw, breaks = 40)
})
})
}
My problem is: I do not get any histogram! I get just the which is nice however, not entirely my goal!
Any idea what could be the reason?
Something like this works:
ui.R
library("shiny")
# Define UI for dataset viewer app ----
ui <- fluidPage(
# App title ----
titlePanel("Data plot"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Selector for choosing dataset ----
selectInput(inputId = 'date',
label = 'Choose a date:',
choices = list.files(path = "./data",
full.names = FALSE,
recursive = FALSE))
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot")
)
)
)
server.R
# Define server ----
server <- function(input, output) {
dataset <- reactive({
infile <- input$date
if (is.null(infile)){
return(NULL)
}
read.csv(paste0('./data/',infile))
})
output$plot <- renderPlot({
x <- dataset()[,1]
hist(x, breaks = 40)
})
}

Multiple conditional selection criteria in shiny

Probably a simple one:
I have a data.frame such as this:
set.seed(1)
df <- data.frame(name=c("A","A","B","C","B","A"),id=1:6,rep1=rnorm(6),rep2=rnorm(6),rep3=rnorm(6))
In the UI part of the R shiny server I'd like to have a drop-down menu that lists unique(df$name), and then given that selection, in a second drop-down menu I'd like to list all df$id that correspond to that df$name selection (i.e., if the selected name is selected.name, this will be: dplyr::filter(df,name == selected.name)$id). Then given these two selections (which are a unique row in df) I'd like to execute server, which executes this function to plot the given selection:
plotData <- function(selected.df)
{
plot.df <- reshape2::melt(dplyr::select(selected.df,-name,-id))
ggplot2::ggplot(plot.df,ggplot2::aes(x=variable,y=value))+ggplot2::geom_point()+ggplot2::theme_minimal()
}
Here's the shiny code I'm trying:
server <- function(input, output)
{
output$id <- renderUI({
selectInput("id", "ID", choices = unique(dplyr::filter(df,name == input$name)$id))
})
output$plot <- renderPlot({
plotData(selected.df=dplyr::filter(df,name == input$name,id == output$id))
})
}
ui <- fluidPage(
# App title ----
titlePanel("Results Explorer"),
# Sidebar layout with a input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# select name
selectInput("name", "Name", choices = unique(df$name)),
uiOutput("id")
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot")
)
)
)
When I run: shinyApp(ui = ui, server = server), I get the error:
Evaluation error: Reading objects from shinyoutput object not allowed..
What's missing?
Here the option would be have renderUI in the 'server' and uiOuput in 'ui'
-ui
library(shiny)
library(dplyr)
library(ggplot2)
ui <- fluidPage(
# App title ----
titlePanel("Results Explorer"),
# Sidebar layout with a input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# select name
selectInput("name", "Name", choices = unique(df$name)),
uiOutput("idselection")
# select id - this is where I need help
),
# Main panel for displaying outputs ----
mainPanel(
# ShinyServer part
plotOutput("plot")
)
)
)
-server
server = function(input, output) {
output$idselection <- renderUI({
selectInput("id", "ID", choices = unique(df$id[df$name ==input$name]))
})
output$plot <- renderPlot({
df %>%
count(name) %>%
ggplot(., aes(x = name, y = n, fill = name)) +
geom_bar(stat = 'identity') +
theme_bw()
})
}
shinyApp(ui = ui, server = server)
-output
Ok, tiny fix:
Create data:
set.seed(1)
df <- data.frame(name=c("A","A","B","C","B","A"),id=1:6,rep1=rnorm(6),rep2=rnorm(6),rep3=rnorm(6))
Function that server will execute:
plotData <- function(selected.df)
{
plot.df <- reshape2::melt(dplyr::select(selected.df,-name,-id))
ggplot2::ggplot(plot.df,ggplot2::aes(x=variable,y=value))+ggplot2::geom_point()+ggplot2::theme_minimal()
}
shiny code:
server <- function(input, output)
{
output$id <- renderUI({
selectInput("id", "ID", choices = unique(dplyr::filter(df,name == input$name)$id))
})
output$plot <- renderPlot({
plotData(selected.df=dplyr::filter(df,name == input$name,id == input$id))
})
}
ui <- fluidPage(
# App title ----
titlePanel("Results Explorer"),
# Sidebar layout with a input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# select name
selectInput("name", "Name", choices = unique(df$name)),
uiOutput("id")
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot")
)
)
)

Resources