R: get sum from selected Input - r

I am relative new to R and trying to learn on my own.
I want to create in a shiny dashboard a select-field where i can choose products of my Data (.xls) and get a sum returned.
The Input is via selectInput and selectize. This is the part, which works :)
If I choose 1 product i'll get the calories of this product back...so far.
My Problem is that wanna choose more products then 1 and get the sum of the calories. How do i have to identify/search the products of the input field in my table and how do i get the sum of it?
Thanks a lot for your help!
PS: Do you need further info about file? only two columns are important for this: product and calories.
library(dplyr)
library(plotly)
library(readxl)
library(shiny)
library(shinydashboard)
# Daten einlesen
McDaten <- read_excel("~/Desktop/McDaten.xlsx")
McDaten$kcal <- McDaten$`kcal (100g)`
ui <- dashboardPage(
skin="red",
dashboardHeader(title = "Analytics Dashboard", titleWidth = 290),
dashboardSidebar(
width = 290,
sidebarMenu(
menuItem("Virtuelles Menü", tabName = "charts", icon = icon("cutlery"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "charts",
fluidPage(
br(),
fluidRow(
column(4,
selectInput('in6', 'Menü', McDaten$Produkt, multiple=TRUE, selectize=TRUE)),
column(4,infoBoxOutput("progressBox"))
)
)
))))
server <- function(input, output) {
output$progressBox <- renderInfoBox({
b <- McDaten %>%
select(`kcal (Portion)`, Produkt) %>%
filter(McDaten$Produkt %in% input$in6) %>%
summarise(`kcal (Portion)`)
infoBox(
"Progress", paste0(b, " kcal"), icon = icon("list"),
color = "purple", fill = TRUE
)
})
}
shinyApp(ui, server)

We need the choices = unique(McDaten$Produkt) in the 'ui' and in summarise the sum needs to be specified for the column of interest
-ui
ui <- dashboardPage(
skin="red",
dashboardHeader(title = "Analytics Dashboard", titleWidth = 290),
dashboardSidebar(
width = 290,
sidebarMenu(
menuItem("Virtuelles Menü", tabName = "charts", icon = icon("cutlery"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "charts",
fluidPage(
br(),
fluidRow(
column(4,
selectInput('in6', 'Menü',
choices = unique(McDaten$Produkt), multiple=TRUE, selectize=TRUE )),
column(4,infoBoxOutput("progressBox"))
)
)
))))
-server
server <- function(input, output) {
output$progressBox <- renderInfoBox({
b <- McDaten %>%
select(`kcal (Portion)`, Produkt) %>%
filter(Produkt %in% input$in6) %>%
summarise(`kcal (Portion)` = sum(`kcal (Portion)`)) %>%
pull(`kcal (Portion)`)
infoBox(
"Progress", paste0(b, " kcal"), icon = icon("list"),
color = "purple", fill = TRUE
)
})
}
-run the app
shinyApp(ui, server)
-data
set.seed(24)
McDaten <- data.frame(Produkt = sample(LETTERS[1:5], 30, replace = TRUE),
`kcal (Portion)` = sample(1400:2000, 30, replace = TRUE),
stringsAsFactors= FALSE, check.names = FALSE)
McDaten$kcal <- McDaten$`kcal (Portion)`
-output

Related

Cannot specify input dataset in shiny dashboard

I am trying to make a shiny dashboard. I have two datasets, and based upon the selection of the datasets figures will be generate in the tab panels. However, by default only the last dataset that has been loaded/read is selected and I cannot select the first dataset. Even though I have made it default selection.
Below is my code.
library(shinydashboard)
library(uwot)
library(DESeq2)
library(gridExtra)
library(tidyverse)
library(RColorBrewer)
library(DESeq2)
library(pheatmap)
library(DEGreport)
library(vsn)
library(RColorBrewer)
library("genefilter")
library(org.Hs.eg.db)
library(dplyr)
library(tidyverse)
library(fgsea)
library(clusterProfiler)
library(ggplot2)
set_1<-load("C:/Users/abn/Documents/Shiny/DashBoardTutorial/TeData2.RData")
set_2<-load("C:/Users/abn/Documents/Shiny/DashBoardTutorial/TeData1.RData")
data_list = list(set_1=set_1,set_2=set_2)
ui <- dashboardPage(
dashboardHeader(title = "Data Visualizer", titleWidth = 300),
dashboardSidebar(
width = 300,
sidebarMenu(
menuItem("Datasets", icon = icon("cog"),
selectInput("Datasets", "Datasets:", choices = list("sample1" = "set_1", "sample2" = "set_2"),
selected = "set_1")),
menuItem("Quality Control", tabName = "widgets", icon = icon("th")),
menuItem("Differential Genes", tabName = "widgets2", icon = icon("th")),
menuItem("Downstream", tabName = "widgets3", icon = icon("th"))
)
),
## Body content
dashboardBody(
tabItems(
# First tab content
# Second tab content
tabItem(tabName="widgets",
h2("widgets"),
plotOutput("widgets"),
),
tabItem(tabName = "widgets2",
h2("Widgets2 tab content"),
),
tabItem(tabName = "widgets3",
h2("Widgets3 tab content"),
plotOutput("widgets3"),
)
)
)
)
server <- function(input, output) {
datasetInput <- reactive({
df <- data_list[[input$Datasets]]
})
output$widgets <- renderPlot({
datasetInput()
par(mfrow=c(1,2))
boxplot(counts(dds, normalized=F), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Without Normalization")
boxplot(counts(dds, normalized=T), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Normalized")
})
}
shinyApp(ui, server)
I am sure that I am missing a small trick, could anyone of you shiny masters help me out.
Or may be there is a better way to do the above procedure.
Many thanks in advance
Assuming you have access to both datasets, you plot them both and display the selection. Try this
data_list = list(set_1=mtcars,set_2=iris)
ui <- dashboardPage(
dashboardHeader(title = "Data Visualizer", titleWidth = 300),
dashboardSidebar(
width = 300,
sidebarMenu(
menuItem("Datasets", icon = icon("cog"),
selectInput("Datasets", "Datasets:", choices = list("sample1" = "set_1", "sample2" = "set_2"),
selected = "set_1")),
menuItem("Quality Control", tabName = "widgets", icon = icon("th")),
menuItem("Differential Genes", tabName = "widgets2", icon = icon("th")),
menuItem("Downstream", tabName = "widgets3", icon = icon("th"))
)
),
## Body content
dashboardBody(
tabItems(
# First tab content
# Second tab content
tabItem(tabName="widgets",
h2("widgets"),
#plotOutput("widgets"),
uiOutput("widgets")
),
tabItem(tabName = "widgets2",
h2("Widgets2 tab content"),
),
tabItem(tabName = "widgets3",
h2("Widgets3 tab content"),
plotOutput("widgets3"),
)
)
)
)
server <- function(input, output) {
# datasetInput <- reactive({
# df <- data_list[[input$Datasets]]
# })
#
# output$widgets <- renderPlot({
# datasetInput()
# par(mfrow=c(1,2))
#
# boxplot(counts(dds, normalized=F), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Without Normalization")
# boxplot(counts(dds, normalized=T), outline=F, col=dds$condition, medcol = "white", cex.axis=0.6, main="Normalized")
#
# })
output$plot1 <- renderPlot({
boxplot(mpg ~ cyl , data=mtcars)
})
output$plot2 <- renderPlot({
boxplot(Sepal.Length ~ Species , data=iris)
})
output$widgets <- renderUI({
if (input$Datasets=="set_1") { plotOutput("plot1")
}else plotOutput("plot2")
})
}
shinyApp(ui, server)

R Shiny Dynamic Report Download

I have made a dynamic report visually in an r shiny app using renderui. I would like to be able to download this dynamic report but not sure how to correctly create it assuming I am unable to convert a render ui into an html file.
What is the best way to write a dynamic html file that can be displayed in the ui? and then download it?
Below is a minimal reproducible project. The download button is currently just for show.
library(shiny)
library(shinydashboard)
library(dplyr)
library(stringr)
library(DBI)
library(DT)
library(shinycssloaders)
library(lubridate)
library(tidyr)
library(ggplot2)
library(plotly)
library(scales)
ui <- dashboardPage(
dashboardHeader(title = "Key Performance Indicators", titleWidth =300),
dashboardSidebar(width = 300,
sidebarMenu(
menuItem("User Guide", tabName = "userguide", icon = icon("question-circle")),
menuItem("Dashboard", tabName = "dashboard", icon = icon("chart-line"), selected = TRUE)
),
selectizeInput(inputId="goals",
label="Goal:",
choices= c("Asset Management"
),
selected= "Asset Management",
multiple = FALSE),
uiOutput("kpis")
),
dashboardBody(
tabItems(
tabItem(
tabName = "userguide",
fluidRow(column(width = 12,
tabBox(width = NULL,
tabPanel("User Guide",
h3("General"),
h5("")
)
)
)
)
),
tabItem(
tabName = "dashboard",
fluidRow(column(width = 12,
tabBox(width = NULL,
tabPanel("Plot",
plotlyOutput("plot", height = 550) %>%
withSpinner(color="#1b6d96")),
tabPanel("Report",
uiOutput("report") %>%
withSpinner(color="#1b6d96")
)
)
)
)
)
)
)
)
server <- function(input, output) {
rawTable <- reactive({
df <- data.frame(KPI =c("Money Spent"),
measure = c("Dollars"),
FY2015= c(500),
FY2016= c(100),
FY2017= c(250),
FY2018= c(600),
FY2019= c(750),
FY2020= c(900))
return(df)
})
output$kpis <- renderUI({
selectizeInput(inputId="kpi",
label="KPI:",
choices= unique(rawTable()$KPI),
selected= unique(rawTable()$KPI[1]),
multiple = FALSE)
})
KPIplot <- reactive({
req(input$kpi)
df <- rawTable() %>%
filter(KPI == input$kpi) %>%
tidyr::pivot_longer(cols = tidyr::starts_with("FY"),
names_to = "Fiscal.Year",
values_to = "Value") %>%
mutate(Values = as.numeric(gsub("[^A-Za-z0-9;._-]","",Value)))
#measure <- toupper(unique(df$`Y Axis Label`))
ggplotly(
ggplot(
data = df,
aes(x = Fiscal.Year, y= Value,
text = paste0("Fiscal Year: ", gsub("\\.","-",str_remove(Fiscal.Year, "FY")),
"<br>Value: ", Value))
) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = comma, breaks = scales::pretty_breaks(n = 10)) +
theme_minimal(),
tooltip = c("text")
)
})
output$plot <- renderPlotly({KPIplot()})
output$report <- renderUI({
fluidPage(
fluidRow(
column(
8, align = "right", offset = 2,
downloadButton("report", "Generate report")
)
),
fluidRow(
column(
8, align="center", offset = 2,
h1("Key Performance Indicator"),
hr(),
h2(input$goals)
)
),
fluidRow(
column(
8, align="left", offset = 2,
h2(input$kpi),
br(),
h3("Description"),
h5("custom text"),
br(),
h3("Performance Data"),
renderPlotly({KPIplot()}),
br(),
h3("Analysis"),
h5("custom text")
)
)
)
})
}
# Run the application
shinyApp(ui = ui, server = server)

Leafletoutput does not show in dashboardBody

Hi I am using shinydashboard to build some visualization for some raster files. I am use leafletOutput to display the map.
Under the first tabItem, where it is called 'KmeansOutput', I would like to display the leaflet map. When I do not include selectInput, it display the map, but once I include the selectInput, it do not display the map. I am not sure which part went wrong. Thanks in advance!!
Here is the UI section of the code:
library(shinydashboard)
library(leaflet)
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("KmeansOutput", tabName = "kmeans", icon = icon("kmeans"),
selectInput("run1",
"SoilAllWeatherAll",
choices = c('4' = 1, '5' = 2),
multiple = TRUE)
),
menuItem("HistoricalWeather", icon = icon("weather"), tabName = "weather"),
menuItem("SoilMap", icon = icon("soil"), tabName = "soil")
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "kmeans",
leafletOutput("map", height = 700)
),
tabItem(tabName = "weather",
h2("weather")),
tabItem(tabName = "soil",
h2('soil'))
)
)
# Put them together into a dashboardPage
ui <- dashboardPage(
dashboardHeader(title = "Genome Prediction"),
sidebar,
body)
here is the server:
server <- function(input, output) {
output$map <- renderLeaflet({
leaflet() %>%
addTiles()
})
}
shinyApp(ui, server)
You need to add a sub-item to your k-means siderbar item as follows.
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("KmeansOutput", #icon = icon("kmeans"),
menuSubItem(
"K-Means Map", tabName = "kmeans", icon = icon("calendar")
),
selectInput("run1",
"SoilAllWeatherAll",
choices = c('4' = 1, '5' = 2),
multiple = TRUE)
),
menuItem("HistoricalWeather", tabName = "weather"), #icon = icon("weather"),
menuItem("SoilMap", tabName = "soil")#, icon = icon("soil")
)
)

How to add a reactive for loop in Shiny R?

I'm trying to create a dashboard using Shiny. Here is some sample data:
###Creating Data
name <- c("Sharon", "Megan", "Kevin")
x <- c(5, 7,3)
y <- c(3,6,2)
z <- c(2,3,7)
jobForm = data.frame(name, x, y, z)
What I'm trying to figure out is, for every row of names how do I create their own TABLE? I believe there is a way to create a reactive for-loop but I've been at this for a long time and have given up.
Here is the full code of what the dashboard should look like for each name. This code only shows Sharon's scores, and it should run. If there are any issues on getting the code to run completely let me know.
I am using
packages shiny, shinydashboard and tidyverse
##Dashboard Header
header <- dashboardHeader(
title = "My Project")
##Dashboard Sidebar
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", icon = icon("dashboard"),tabName = "dashboard"),
menuItem("Job Positions", icon = icon("address-card"), tabName = "jobposition",
menuSubItem('Sales',
tabName = 'sales',
icon = icon('line-chart'))
)
)
)
##Dashboard Body
body <- dashboardBody(
tabItems(
# Dashboard Tab Content
tabItem(tabName = "dashboard",
fluidRow(
#Random Plot
box( )
)
),
# Associate Tab Content
tabItem(tabName = "sales",
fluidRow(
#Main Box for Candidate
box(
width = 8,
title = "Candidate 001",
status = "primary",
#Box for Table
box(
title = "Table",
status = "info",
tableOutput("stat1")
)
)
)
)
)
)
##User Interface Using Dashboard Function
ui <- dashboardPage(
skin = "yellow",
header,
sidebar,
body
)
##Server: Instructions
server <- function(input, output) {
temp <- data.frame(jobForm %>%
slice(1) %>%
select(x:z))
temp <- as.data.frame(t(temp))
output$stat1 <-renderTable({
temp
},
include.rownames=TRUE,
colnames(temp)<-c("Score")
)
}
##Create Shiny App Object
shinyApp(ui, server)
Thank you for any help
You better solve these kibnd of problems with an renderUI and since you never really know when shiny will evaluate an expression you are much better of using lapply then for loops.
name <- c("Sharon", "Megan", "Kevin")
x <- c(5, 7,3)
y <- c(3,6,2)
z <- c(2,3,7)
jobForm = data.frame(name, x, y, z)
##Dashboard Header
header <- dashboardHeader(
title = "My Project")
##Dashboard Sidebar
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", icon = icon("dashboard"),tabName = "dashboard"),
menuItem("Job Positions", icon = icon("address-card"), tabName = "jobposition",
menuSubItem('Sales',
tabName = 'sales',
icon = icon('line-chart'))
)
)
)
##Dashboard Body
body <- dashboardBody(
tabItems(
# Dashboard Tab Content
tabItem(tabName = "dashboard",
fluidRow(
#Random Plot
box( )
)
),
# Associate Tab Content
tabItem(tabName = "sales",
fluidRow(
#Main Box for Candidate
uiOutput("candidates")
)
)
)
)
##User Interface Using Dashboard Function
ui <- dashboardPage(
skin = "yellow",
header,
sidebar,
body
)
##Server: Instructions
server <- function(input, output) {
temp <- data.frame(jobForm %>%
slice(1) %>%
select(x:z))
temp <- as.data.frame(t(temp))
output$stat1 <-renderTable({
temp
},
include.rownames=TRUE,
colnames(temp)<-c("Score")
)
output$candidates <- renderUI(
tagList(
lapply(1:nrow(jobForm), function(idx){
output[[paste0("stat",idx)]] <- renderTable(
jobForm[idx,-1]
)
box(
width = 8,
title = paste0("Candidate: ",jobForm$name[idx]),
status = "primary",
#Box for Table
box(
title = "Table",
status = "info",
tableOutput(paste0("stat",idx))
)
)
})
)
)
}
##Create Shiny App Object
shinyApp(ui, server)
Hope this helps!!

Set the x-axis of a line graph based on a shiny dateRangeInput()

Hello I have a simple shiny app which includes a line graph. Firstly the user selects BOTH CHOICES of the checkboxgroup then the dateRangeInput() loads the relative dates and then I want to be able to create a line graph which will have this date range in the x-axis. I am not sure which is the correct way to give the date range as input to my plot.
OriginId = c("INT", "DOM", "INT","DOM","INT","DOM")
RequestedDtTm = c("2017-01-16 16:43:33
", "2017-01-17 16:43:33
", "2017-01-18 16:43:33
","2017-01-19 16:43:33",
"2017-01-18 16:43:33
","2017-01-19 16:43:33" )
ClientZIP=c(20000,24455,56000,45000,80000,45000)
testdata = data.frame(OriginId,RequestedDtTm,ClientZIP)
## ui.R ##
library(shinydashboard)
library(plotly)
dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody()
)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
## Sidebar content
dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
menuItem("Change View", tabName = "widgets", icon = icon("th"))
)
),
## Body content
dashboardBody(
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidRow(
box(plotlyOutput("plot3",height = 250))
)
),
# Second tab content
tabItem(tabName = "widgets",
fluidRow(
box(title="Line Graph",width = 12,
column(4,
checkboxGroupInput("checkGroup4", label = h3("Checkbox group"),
choices = list("Show Domestic" = "DOM", "Show International" = "INT"),
selected = "DOM")
),
column(4,
uiOutput("dt3")
),
column(4,
uiOutput("n3")
)
))
)
)
)
)
server <- function(input, output) {
output$plot3 <- renderPlotly({
data<-subset(testdata[,c(2,3)],testdata$OriginId %in% input$checkGroup4)
p <- plot_ly(data, x = format(as.Date(input$dateRange3), "%Y-%m"), y = ~ClientZIP, type = 'scatter', mode = 'lines')
})
output$dt3<-renderUI({
dateRangeInput('dateRange3',
label = 'Date range',
start = min(subset(as.POSIXct(testdata$RequestedDtTm),testdata$OriginId %in% input$checkGroup4)), end = max(subset(as.POSIXct(testdata$RequestedDtTm),testdata$OriginId %in% input$checkGroup4))
)
})
}
Here is a working example. When using dateRangeInput() you need to extract both, min (input$dateRange3[1]) and max (input$dateRange3[2]) values. Hope it helps.
OriginId = c("INT", "DOM", "INT","DOM","INT","DOM")
RequestedDtTm = c("2017-01-16", "2017-01-17", "2017-01-18","2017-01-19", "2017-01-18","2017-01-19")
ClientZIP=c(20000,24455,56000,45000,80000,45000)
testdata = data.frame(OriginId,RequestedDtTm,ClientZIP)
dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody()
)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
## Sidebar content
dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
menuItem("Change View", tabName = "widgets", icon = icon("th"))
)
),
## Body content
dashboardBody(
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidRow(
box(plotlyOutput("plot3"))
)
),
# Second tab content
tabItem(tabName = "widgets",
fluidRow(
box(title="Line Graph",width = 12,
column(4,
checkboxGroupInput("checkGroup4", label = h3("Checkbox group"),
choices = list("Show Domestic" = "DOM", "Show International" = "INT"),
selected = "DOM")
),
column(4,
uiOutput("dt3")
),
column(4,
uiOutput("n3")
)
))
)
)
)
)
server <- function(input, output) {
output$plot3 <- renderPlotly({
data <- dplyr::tbl_df(subset(testdata[,c(2,3)],testdata$OriginId %in% input$checkGroup4))
date_start <- as.character(input$dateRange3[1])
date_end <- as.character(input$dateRange3[2])
data$RequestedDtTm <- as.Date(data$RequestedDtTm, format = "%Y-%m-%d")
# data <- data %>% filter(RequestedDtTm >= date_start & RequestedDtTm <= date_end)
data <- data[as.Date(data$RequestedDtTm) >= date_start & as.Date(data$RequestedDtTm) <= date_end, ]
p <- plot_ly(data, x = ~RequestedDtTm, y = ~ClientZIP, type = 'scatter', mode = 'lines')
})
output$dt3<-renderUI({
dateRangeInput('dateRange3',
label = 'Date range',
start = min(subset(as.POSIXct(testdata$RequestedDtTm),testdata$OriginId %in% input$checkGroup4)), end = max(subset(as.POSIXct(testdata$RequestedDtTm),testdata$OriginId %in% input$checkGroup4))
)
})
}
shinyApp(ui, server)

Resources