To allign text to the rightmost region of shinydashboard :R - r

DATA
I want to add text in rightmost region in the dashboard and the text should cover all the right space column.
dashboardPage(skin="yellow",
dashboardHeader(title = "Wheat Price dashboard ),
dashboardSidebar(
sidebarMenu(
menuItem("Punjab-khanna", tabName = "dashboard", icon = icon("area-chart"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "dashboard",
fluidPage(
titlePanel("Wheat DARA"),
mainPanel(fluidRow(
box( side="right",
tabPanel("Price chart", dygraphOutput("plot1")
)
),box(side = "right",height="250px",includeMarkdown("read.md")))
) )
)
))
)
SERVER.R
d1<-read_excel("data/Wheat data forecasted.xlsx",sheet = 1,col_names =
TRUE)
#stock
d2 <-subset(d1, select = c(1,2,3,4,5))
#last
d1 <-subset(d1, select = c(1,5,6,7))
d1$`Date GMT` <- as.POSIXct(d1$`Date GMT`, format = "%Y-%m-%d", tz="GMT")
ts1 <- irts(time=d1$`Date GMT`,value=as.matrix(d1[,2:4]))
#stock
d2$`Date GMT` <- as.POSIXct(d2$`Date GMT`, format = "%Y-%m-%d", tz="GMT")
ts2 <- irts(time=d2$`Date GMT`,value=as.matrix(d2[,2:5]))
shinyServer(function(input, output) {
output$plot1 <- renderDygraph({
dygraph(ts1) %>%
dyRangeSelector() %>%
dyLegend(show = "always", hideOnMouseOut = FALSE) %>%
dyHighlight(highlightCircleSize = 5) %>%
dyOptions(axisLineColor = "navy", gridLineColor = "grey")
})
} )
I am not able to arrange it to the right side.
NOTE:I have written different text(from the image) but the task is same to arrange the text to rightmost region in dashboard

I've added a minimal reproducible code myself. Please check. You just have to play with fluidrow and column with width values.
if(interactive()) {
## app.R ##
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
column(
column(
fluidRow(
box(plotOutput("plot1"))
),
fluidRow(
box(plotOutput("plot2"))
),
width = 10
),
column(
h3(
textOutput('text1')
),
width = 2
),
width = 12
)
)
)
)
server <- function(input, output) {
set.seed(122)
histdata <- rnorm(500)
output$plot1 <- renderPlot({
hist(histdata)
})
output$plot2 <- renderPlot({
hist(histdata)
})
output$text1 <- renderText({
"Uniform: These functions provide information about the uniform distribution on the interval from min to max. dunif gives the density, punif gives the distribution function qunif gives the quantile function and runif generates random deviates."
})
}
shinyApp(ui, server)
}
Source Code modified:
Please modify your dashboard input like this below. It also has plot2, since your initial question had one.
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
column(
column(
fluidRow(
tabPanel("Price chart", dygraphOutput("plot1")
),
fluidRow(
plotOutput("plot2")
),
width = 10
),
column(
h3(
includeMarkdown("read.md")
),
width = 2
),
width = 12
)
)
)

Related

Embedding functions into selectizeinput in shinydashboard

I am trying to add functions to the selectizeInput holder in my shinydashboard to use them interactively on my dataframe. Is there a way to display a name for each function (e.g monthly and annual) instead of having the function itself printed out?
ibrary(shiny)
library(shinydashboard)
annual <- function(x){
(x/lag(x, 12) - 1)*100
}
monthly <- function(x){
(x/lag(x) - 1)*100
}
ui <- dashboardPage(
dashboardHeader(title = 'Dashboard'),
dashboardSidebar(sidebarMenu
(menuItem(tabName = 'Panel1', text = 'Panel 1')
)
),
dashboardBody(
tabItems(tabItem(tabName = 'Panel1',
fluidRow(box(selectizeInput('select', 'Select',
choices = c(monthly, annual)),height=80,width=4,
)
),
fluidRow(box(width = 13, height = 655))
)
)
)
)
server <- function(input, output) {
}
shinyApp(ui, server)
You could use a named vector to add labels for the choices:
library(shiny)
library(shinydashboard)
annual <- function(x) {
(x / lag(x, 12) - 1) * 100
}
monthly <- function(x) {
(x / lag(x) - 1) * 100
}
ui <- dashboardPage(
dashboardHeader(title = "Dashboard"),
dashboardSidebar(sidebarMenu
(menuItem(tabName = "Panel1", text = "Panel 1"))),
dashboardBody(
tabItems(tabItem(
tabName = "Panel1",
fluidRow(box(selectizeInput("select", "Select",
choices = c("monthly" = monthly, "annual" = annual)
), height = 80, width = 4, )),
fluidRow(box(width = 13, height = 655))
))
)
)
server <- function(input, output) {
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:6875

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)

R highcharter, valuebox, eventreactive didn't work together in shiny

I want to build an app by shinydashboard that work like this:
textInput
Submit actionbutton to update value box based in input text
valuebox (to show input text)
Tabbox with 5 tabpanel
Each tabpanel has histogram with different data and rendered by Highcharter
VerbatimTextOutput to indivate which tabpanel chosen
This is my code:
library(shiny)
library(shinydashboard)
library(highcharter)
### Data ================================================
set.seed(1)
Ext <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(2)
Con <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(3)
Agr <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(4)
Emo <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(5)
Int <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
### Apps Atribut ========================================
header <- dashboardHeader(
title = "IPIP-BFM-50"
)
sidebar <- dashboardSidebar()
body <- dashboardBody(
fluidRow(
box(
textInput(
"unicode",
"Your Unique ID:",
placeholder = "Input your unique ID here"
),
actionButton(
"ab1_unicode",
"Submit"
),
width = 6
),
tags$head(tags$style(HTML(".small-box {height: 130px}"))),
valueBoxOutput(
"vbox1_unicode",
width = 6
)
),
fluidRow(
tabBox(
title = "Dimensi Big-Five Marker",
id = "tabset1",
height = "500px",
width = 12,
tabPanel(
"Extraversion",
"This is Extraversion",
highchartOutput(
"hist"
)
),
tabPanel(
"Conscientiousness",
"This is Conscientiousness",
highchartOutput(
"hist"
)
),
tabPanel(
"Agreeableness",
"This is Agreeableness",
highchartOutput(
"hist"
)
),
tabPanel(
"Emotional Stability",
"This is Emotional Stability",
highchartOutput(
"hist"
)
),
tabPanel(
"Intelligent",
"This is Intelligent",
highchartOutput(
"hist"
)
)
)
),
fluidRow(
box(
"Personality in a nutshell", br(),
"Second row of personality explanation",
verbatimTextOutput(
"tabset1selected"
),
width = 12,
height = "250px"
)
)
)
### Atribut server
### Apps ================================================
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output){
update_unicode <- eventReactive(input$ab1_unicode,{
input$unicode
}, ignoreNULL = F)
output$vbox1_unicode <- renderValueBox({
valueBox(
update_unicode(),
"Your Unique ID",
icon = icon("fingerprint")
)
})
dimension <- function(dim){
if(dim == "Extraversion"){
Ext
} else if(dim == "Conscientiousness"){
Con
} else if(dim == "Agreeableness"){
Agr
} else if(dim == "Emotional Stability"){
Emo
} else if(dim == "Intelligent"){
Int
}
}
output$hist <- renderHighchart({
hchart(
dimension(input$tabset1)
) %>%
hc_xAxis(
list(
title = list(
text = "Data"
),
plotBands = list(
color = '#3ac9ad',
from = update_unicode,
to = update_unicode,
label = list(
text = "Your Score",
color = "#9e9e9e",
align = ifelse(update_unicode>30,"right","left"),
x = ifelse(update_unicode>30,-10,+10)
)
)
)
)
})
output$tabset1selected <- renderText({
input$tabset1
})
}
shinyApp(ui = ui,server = server)
Problems:
valuebox dissapear
highchart didn't appear
I made only 1 histogram with conditions to save the efeciency. but it looks didn't work well.
This is what the result looked like
Please help me guys
The issue is that the the binding between an id in the UI and on the server side has to be unique. However, in your dashboard the id="hist" appears more than once in the UI, i.e. you have a duplicated binding.
This could be seen by 1. opening the dashboard in the Browser, 2. opening the dev tools 3. having a look the console output which shows a JS error message "Duplicate binding for id hist".
Not sure about your final result but to solve this issue you could e.g. add one highchartOutput per panel. To this end:
I have put the plotting code in a separate function make_hc
Added an highchartOutput for each of your panels or datasets, e.g.
output$hist1 <- renderHighchart({
make_hc("Extraversion", update_unicode())
})
This way we get 5 outputs with unique ids which could be put inside the respective panels in the UI.
Full reproducible code:
library(shiny)
library(shinydashboard)
library(highcharter)
### Data ================================================
set.seed(1)
Ext <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(2)
Con <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(3)
Agr <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(4)
Emo <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
set.seed(5)
Int <- round(rnorm(500,runif(1,25,35),runif(1,4,12)))
### Apps Atribut ========================================
header <- dashboardHeader(
title = "IPIP-BFM-50"
)
sidebar <- dashboardSidebar()
body <- dashboardBody(
fluidRow(
box(
textInput(
"unicode",
"Your Unique ID:",
placeholder = "Input your unique ID here"
),
actionButton(
"ab1_unicode",
"Submit"
),
width = 6
),
tags$head(tags$style(HTML(".small-box {height: 130px}"))),
valueBoxOutput(
"vbox1_unicode",
width = 6
)
),
fluidRow(
tabBox(
title = "Dimensi Big-Five Marker",
id = "tabset1",
height = "500px",
width = 12,
tabPanel(
"Extraversion",
"This is Extraversion",
highchartOutput(
"hist1"
)
),
tabPanel(
"Conscientiousness",
"This is Conscientiousness",
highchartOutput(
"hist2"
)
),
tabPanel(
"Agreeableness",
"This is Agreeableness",
highchartOutput(
"hist3"
)
),
tabPanel(
"Emotional Stability",
"This is Emotional Stability",
highchartOutput(
"hist4"
)
),
tabPanel(
"Intelligent",
"This is Intelligent",
highchartOutput(
"hist5"
)
)
)
),
fluidRow(
box(
"Personality in a nutshell", br(),
"Second row of personality explanation",
verbatimTextOutput(
"tabset1selected"
),
width = 12,
height = "250px"
)
)
)
### Atribut server
### Apps ================================================
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output){
update_unicode <- eventReactive(input$ab1_unicode,{
input$unicode
}, ignoreNULL = F)
output$vbox1_unicode <- renderValueBox({
valueBox(
update_unicode(),
"Your Unique ID",
icon = icon("fingerprint")
)
})
dimension <- function(dim){
if(dim == "Extraversion"){
Ext
} else if(dim == "Conscientiousness"){
Con
} else if(dim == "Agreeableness"){
Agr
} else if(dim == "Emotional Stability"){
Emo
} else if(dim == "Intelligent"){
Int
}
}
make_hc <- function(x, update_unicode) {
hchart(
dimension(x)
) %>%
hc_xAxis(
list(
title = list(
text = "Data"
),
plotBands = list(
color = '#3ac9ad',
from = update_unicode,
to = update_unicode,
label = list(
text = "Your Score",
color = "#9e9e9e",
align = ifelse(update_unicode>30,"right","left"),
x = ifelse(update_unicode>30,-10,+10)
)
)
)
)
}
output$hist1 <- renderHighchart({
make_hc("Extraversion", update_unicode())
})
output$hist2 <- renderHighchart({
make_hc("Conscientiousness", update_unicode())
})
output$hist3 <- renderHighchart({
make_hc("Agreeableness", update_unicode())
})
output$hist4 <- renderHighchart({
make_hc("Emotional Stability", update_unicode())
})
output$hist5 <- renderHighchart({
make_hc("Intelligent", update_unicode())
})
output$tabset1selected <- renderText({
input$tabset1
})
}
shinyApp(ui = ui,server = server)

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

R: get sum from selected Input

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

Resources