Cannot specify input dataset in shiny dashboard - r

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)

Related

Reset in Shiny applications

I am trying to clear what ever is written in the text area but looks like it not working. Based on the below applications, when the user clicks on "click" button, the contents (if written) should get cleared. But it is not. Can anyone help me here please........................................
data(mtcars)
library(shiny)
library(shinydashboard)
library(dplyr)
library(DT)
library(shinyjs)
ui <- dashboardPage(
dashboardHeader(title = "Dynamic sidebar"),
dashboardSidebar(sidebarMenu(id = "menu", sidebarMenuOutput("menu"))),
dashboardBody(tabItems
(
tabItem
(tabName = "plots", h2("Dashboard plots"),
fluidRow(column(width = 12, class = "well",
h4("Boxplot"),
plotOutput("bxp")))
),
tabItem(tabName = "dashboard", h2("Dashboard tab content"),
dataTableOutput(outputId = "subdt"),textAreaInput("sd","label1"),textAreaInput("sd1","label2") ,
actionButton("idff","click"))
)
)
)
server <- function(input, output, session) {
output$menu <- renderMenu({
sidebarMenu(
# menuItem("Plots Menu", tabName = "plots", icon = icon("line-chart")),
menuItem("Table Menu", icon = icon("info"),
menuSubItem(
"Dashboard", tabName = "dashboard", icon = icon("calendar")
),
selectInput(
inputId = "mcm", label = "Some label", multiple = TRUE,
choices = unique(mtcars$cyl), selected = unique(mtcars$cyl)
)
)
)
})
observe({
print(input$menu)
})
datsub <- reactive({
mtcars %>%
filter_at(vars("cyl"), all_vars(. %in% input$mcm))
})
output$subdt <- renderDataTable({
datatable(datsub(),selection = if(input$menu == "dashboard"){'single'} else {'none'})
# print(datatable.selection())
})
# datatable(datsub(),selection = if(input$menu == "dashboard"){'single'} else {'none'})
output$bxp <- renderPlot({
hist(rnorm(100))
})
observeEvent(input$idff,{
print("cjec")
shinyjs::reset('sd')
shinyjs::reset('sd1')
})
}
shinyApp(ui, server)
I'd suggest to update the textAreaInput as suggested in the comments. Update the event handler as follows:
observeEvent(input$idff, {
updateTextAreaInput(session = session, inputId = 'sd', value = "")
updateTextAreaInput(session = session, inputId = 'sd1', value = "")
})

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)

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

Trouble with a Reactive Input in ShinyDashboard

I am using the following dataset: https://docs.google.com/spreadsheets/d/1C_P5xxzYr7HOkaZFfFiDhanqDSuSIrd2UkiC-6_G2q0/edit#gid=0
I am using ShinyDashboard and I have a selectInput that allows me to choose a specific type of Candy bar (in the Candy column in my data set).
How do I take that Candy selection, and then make a graph that contains the frequency for that selected candy bar for each purchase month? In my server.R, I am not sure what to have in that CandyCount reactive element.
My code is as follows:
## ui.R ##
library(shinydashboard)
library(rCharts)
dashboardPage(
dashboardHeader(title = "Dashboard"),
dashboardSidebar(
width = 150,
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("bar-chart"))
)
),
dashboardBody(
sidebarPanel(
htmlOutput("candy")
),
mainPanel(
showOutput("plot2", "polycharts")
)))
##server.R##
server <- function(input, output, session) {
output$candy<- renderUI({
selectInput(
inputId = "candy",
label = "Candy: ",
choices = as.character(unique(dataset$Candy)),
selected = "Twix"
)
})
output$plot2 <- renderChart2({
candySelect<- input$candy
df <- dataset[dataset$candy == candySelect,]
p2 <- rPlot(freq~purchase_month, data = df, type = 'line')
p2$guides(y = list(min = 0, title = ""))
p2$guides(y = list(title = ""))
p2$addParams(height = 300, dom = 'chart2')
return(p2)
})
}
If your okay with using ggplot you could do something like this:
Edited to have dynamic tooltip
## ui.R ##
library(shinydashboard)
library(shinyBS)
require(ggplot2)
dataset <- read.csv("Sample Dataset - Sheet1.csv")
ui <- dashboardPage(
dashboardHeader(title = "Dashboard"),
dashboardSidebar(
width = 150,
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("bar-chart"))
)
),
dashboardBody(
sidebarPanel(
htmlOutput("candy")
),
mainPanel(
uiOutput("plotUI")
)
))
##server.R##
server <- function(input, output, session) {
output$candy<- renderUI({
selectInput(
inputId = "candy",
label = "Candy: ",
choices = as.character(unique(dataset$Candy)),
selected = "Twix"
)
})
output$plotUI <- renderUI({
if(is.null(input$candy)) return(NULL)
local({
candySelect <- input$candy
str1 <- sprintf("The candybar you selected is: %s",candySelect)
str2 <- sprintf("More about %s <a>here</a>",candySelect)
print (str1)
popify(plotOutput('plot'),str1,str2)
})
})
observeEvent(input$candy,{
if(is.null(input$candy)) return(NULL)
candySelect<- input$candy
print ('plot')
# Assuming only one entry for each mont per candybar
d <- dataset[dataset$Candy==candySelect,]
output$plot <- renderPlot({
ggplot(data=d, aes(x=purchase_month,y=freq,group=Candy)) +
geom_line() +
ggtitle(candySelect)
})
})
}
shinyApp(ui = ui, server = server)
I guess this should work otherwise you can bind tooltips using jQuery.

Resources