Any chance using input$radio button as argument in group_by - shiny

I have tried to use radio button as an argument in group_by. Since I'm new to Shiny with no JS script background so quite being blind in render/output. and how to adapt with normal R-code.
Please show me some useful document/example in applying input to normal R-code
(not as simple as what's shown in shiny- widget gallery)
dat <- read_csv("VN_MAT as of 202001.csv")
datasetInput <- reactive({
switch(input$radio3,
"A" = "PROD_MANUFACTURER, PROD_BRAND, MKT_SDESC",
"B" = "PROD_MANUFACTURER, PROD_LDESC, MKT_SDESC" )
})
dat_brand <- reactive({
dat %>%
data.frame() %>%
group_by(datasetInput()) %>%
summarise(PER_MAT.TY = round(sum(PER_MAT.TY),digit = 2), PER_MAT.YA = round(sum(PER_MAT.YA), digit
=2)) %>%
arrange(MKT_SDESC) %>%
data.frame() %>%
add_count(MKT_SDESC, wt = PER_MAT.TY) %>%
mutate("VALUE_SHARE_TY" = round(PER_MAT.TY/n, digit = 4)) %>%
select(-n) %>%
add_count(MKT_SDESC, wt = PER_MAT.YA) %>%
mutate("VALUE_SHARE_LY" = round(PER_MAT.YA/n, digit = 4)) %>%
select(-n) %>%
mutate("DIFF_SHARE_YA" = round(VALUE_SHARE_TY - VALUE_SHARE_LY, digit = 4)) %>%
mutate("VALUE_GROWTH" = round(PER_MAT.TY/PER_MAT.YA - 1, digit =4))
})

After trial & error, I can figure out the answer as following code
I have overcome it with using if + choice of code
server <- function(input, output, session){
library(shiny)
library(ggplot2)
library(tidyverse)
Principal <- c("a","a","a","a","b","b","b","b","c","c")
Value <- as.numeric(c(4,1,1,3,4,2,2,3,2,1))
g <- c("t1","t1","t1","t1","t1","t2","t2","t2","t2","t2")
b <- as.numeric(c(4,1,1,3,4,2,2,3,2,1))
df <- data.frame(Principal,Value,g,b)
output$plot <- renderPlot({
if(input$radio1 == 1){
df%>%
group_by(g,b) %>%
summarize(total = sum(Value)) %>%
ggplot(aes(x = total, y = b))+
geom_point()
}else{
df%>%
group_by(Principal,b) %>%
summarize(total = sum(Value)) %>%
ggplot(aes(x = total, y = b))+
geom_point()}
})
}
ui <- basicPage(
radioButtons(
inputId = "radio1",
label = "Radio1",
choices = c(1, 2)
),
plotOutput("plot")
)
shinyApp(ui = ui, server = server)

Related

Leaflet map initially doesn't render markers when inside a tabpanel in shiny [duplicate]

This question already has an answer here:
Leaflet in another tab not updated with leafletproxy before visiting tab
(1 answer)
Closed 11 months ago.
I want to present a leaflet map inside a tabpanel in Shiny. The problem, however, is that the data point circles don't render ininitially. Only after I move the slider the circles show up on the map. Is it possible to show the circles when I click on the tabpanel?
Here is an example using the quakes data.
library(shiny)
library(leaflet)
ui <- navbarPage("Shiny app",
tabPanel("Empty"),
navbarMenu("Quakes",
tabPanel("Quakes map",
bootstrapPage(
sidebarLayout(
sidebarPanel(top = 10, right = 10,
sliderInput("range", "Magnitudes", min(quakes$mag), max(quakes$mag),
value = range(quakes$mag), step = 0.1)
),
mainPanel(
leafletOutput("map")
)
)
)
)
)
)
server <- function(input, output, session) {
filteredData <- reactive({
quakes[quakes$mag >= input$range[1] & quakes$mag <= input$range[2],]
})
output$map <- renderLeaflet({
leaflet(quakes) %>% addTiles() %>%
fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
})
observe({
leafletProxy("map", data = filteredData()) %>%
clearShapes() %>%
addCircles(radius = ~10^mag/10, weight = 1, color = "#777777",
fillOpacity = 0.7, popup = ~paste(mag)
)
})
}
shinyApp(ui, server)
There's no reason to use output$map and a proxy just to use the reactive data (or maybe I missed something). You can simply use filteredData() in your original renderLeaflet():
server <- function(input, output, session) {
filteredData <- reactive({
quakes[quakes$mag >= input$range[1] & quakes$mag <= input$range[2],]
})
output$map <- renderLeaflet({
leaflet(filteredData()) %>% addTiles() %>%
fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat)) %>%
addCircles(radius = ~10^mag/10, weight = 1, color = "#777777",
fillOpacity = 0.7, popup = ~paste(mag)
)
})
}

Sorting the numbers when units are added

I am trying to add the units to numbers in the dataframe. But I see after formatting, sorting is not working as expected (since the column is now characters). I need to sort as per numbers only (Millions coming at last). But this is not happening
library(shiny)
library(DT)
ui <- fluidPage(
DTOutput("tab")
)
server <- function(input, output, session) {
format_numbers <- function (df, column_name){
df[[column_name]] <- ifelse(nchar(df[[column_name]]) <= 5, paste(format(round(df[[column_name]] / 1e3, 1), trim = TRUE), "K"),
paste(format(round(df[[column_name]] / 1e6, 1), trim = TRUE), "M"))
}
df <- data.frame(x = c(12345,35666,2646575,345))
df$x <- format_numbers(df, "x")
output$tab <- renderDT({
datatable(df,escape = F)
})
}
shinyApp(ui, server)
You can add a new column and sort by the original one :
library(shiny)
library(DT)
library(dplyr)
ui <- fluidPage(
DTOutput("tab")
)
server <- function(input, output, session) {
format_numbers <- function (df, column_name){
df[[column_name]] <- ifelse(nchar(df[[column_name]]) <= 5, paste(format(round(df[[column_name]] / 1e3, 1), trim = TRUE), "K"),
paste(format(round(df[[column_name]] / 1e6, 1), trim = TRUE), "M"))
}
df <- data.frame(x = c(12345,35666,2646575,345))
df$NewX = format_numbers(df, "x")
df <- df %>% arrange(x)
output$tab <- renderDT({
datatable((df %>% select(-x)),escape = F)
})
}
shinyApp(ui, server)

Add Dynamic Plot Subtitles in Rshiny

What I achieved so far: I have a fully reproducible shiny app (using iris dataset) which makes dynamic plots (one does not know how many plots will output) based on one or more selected dropdown value(s) (Species in this case).
My question: I'd like to add a dynamic subtitle from a column called new. To elaborate, each Species has exactly two unique values (e.g., a and b for Species = setosa). Is there a way to add these unique values so that it could be integrated into the dynamic plots ?
What I tried:
df() %>% select(new) %>% distinct() %>% pull()
However, this does not produce the output I want.
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(tidyverse)
species <- c("setosa", "versicolor", "virginica")
iris %>% filter(Species == "setosa")
vals1 <- rep(c("a", "b"), 25)
vals2 <- rep(c("c", "d"), 25)
vals3 <- rep(c("e", "f"), 25)
vals <- c(vals1, vals2, vals3)
iris <- iris %>%
mutate(new = vals)
ui <- dashboardPage(
dashboardHeader(title = "title"),
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("General Overview", tabName = "tab1", icon = icon("dashboard"))
)
),
body <- dashboardBody(
tabItems(
tabItem(
tabName = "tab1",
uiOutput("species_dropdown"),
DT::dataTableOutput("table1"),
textOutput("text1"),
uiOutput("plots")
)
)
)
)
server <- function(input, output) {
output$species_dropdown <- renderUI({
pickerInput(
"var1",
"Species:",
choices = species,
options = pickerOptions(
actionsBox = T,
header = "Close",
liveSearch = T
),
multiple = T
)
})
filtered_data <- reactive({
map(input$var1, ~ iris %>% filter(Species == .x)) %>% set_names(input$var1)
})
output$plots <- renderUI({
req(input$var1)
plot_output_list <- lapply(input$var1, function(i) {
plotname <- paste("plot_", i, sep = "")
plotOutput(plotname, height = 280, width = 250)
})
do.call(flowLayout, plot_output_list)
})
observeEvent(filtered_data(), {
iwalk(filtered_data(), ~ {
output[[paste0("plot_", .y)]] <<- renderPlot({
ggplot(.x, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
labs(title = .y, x = "Sepal Length", y = "Sepal Width") # how to make and integrate dynamic subtitles from output$text1 ?
})
})
})
df <- reactive({
req(input$var1)
iris %>%
filter(Species == input$var1)
})
output$table1 <- DT::renderDataTable({
df()
})
output$text1 <- renderText({
df() %>% select(new) %>% distinct() %>% pull()
})
}
shinyApp(ui, server)
We can use the information provided by filtered_data and inside the walk function, create during each iteration a variable called subt that will capture the unique values from new column.
observeEvent(filtered_data(), {
iwalk(filtered_data(), ~ {
subt <- pull(., new) %>%
unique() %>%
str_c(collapse = ",")
subt <- paste("Unique values are:", subt)
output[[paste0("plot_", .y)]] <<- renderPlot({
ggplot(.x, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
labs(title = .y, subtitle = subt, x = "Sepal Length", y = "Sepal Width") # how to make and integrate dynamic subtitles from output$text1 ?
})
})
})
Full app:
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(tidyverse)
species <- c("setosa", "versicolor", "virginica")
iris %>% filter(Species == "setosa")
vals1 <- rep(c("a", "b"), 25)
vals2 <- rep(c("c", "d"), 25)
vals3 <- rep(c("e", "f"), 25)
vals <- c(vals1, vals2, vals3)
iris <- iris %>%
mutate(new = vals)
ui <- dashboardPage(
dashboardHeader(title = "title"),
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("General Overview", tabName = "tab1", icon = icon("dashboard"))
)
),
body <- dashboardBody(
tabItems(
tabItem(
tabName = "tab1",
uiOutput("species_dropdown"),
DT::dataTableOutput("table1"),
textOutput("text1"),
uiOutput("plots")
)
)
)
)
server <- function(input, output) {
output$species_dropdown <- renderUI({
pickerInput(
"var1",
"Species:",
choices = species,
options = pickerOptions(
actionsBox = T,
header = "Close",
liveSearch = T
),
multiple = T
)
})
filtered_data <- reactive({
map(input$var1, ~ iris %>% filter(Species == .x)) %>% set_names(input$var1)
})
output$plots <- renderUI({
req(input$var1)
plot_output_list <- lapply(input$var1, function(i) {
plotname <- paste("plot_", i, sep = "")
plotOutput(plotname, height = 280, width = 250)
})
do.call(flowLayout, plot_output_list)
})
observeEvent(filtered_data(), {
iwalk(filtered_data(), ~ {
subt <- pull(., new) %>%
unique() %>%
str_c(collapse = ",")
subt <- paste("Unique values are:", subt)
output[[paste0("plot_", .y)]] <<- renderPlot({
ggplot(.x, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
labs(title = .y, subtitle = subt, x = "Sepal Length", y = "Sepal Width") # how to make and integrate dynamic subtitles from output$text1 ?
})
})
})
df <- reactive({
req(input$var1)
iris %>%
filter(Species == input$var1)
})
output$table1 <- DT::renderDataTable({
df()
})
output$text1 <- renderText({
df() %>%
select(new) %>%
unique() %>%
pull()
})
}
shinyApp(ui, server)

Update dataframe to change leaflet output based on users choice in shiny

I'm new to shiny and I have tried multiple ways to update the leaflet output based on two selectinput, the first chooses the data frame to use and the second what to filter on. this bit is working but I don't seem to be able to pass this to the leaflet proxy, any thoughts would be appreciated
poldat <- vroom::vroom("F:/ming1/data/poldat.csv")
meddat <- vroom::vroom("F:/ming1/data/meddat.csv")
medlist <- vroom::vroom("F:/ming1/data/ddl1.csv")
pollist <- vroom::vroom("F:/ming1/data/ddl2.csv")
library(shiny)
library(leaflet)
library(RColorBrewer)
library(vroom)
ui <- bootstrapPage(
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "50%", height = "100%"),
absolutePanel(top = 10, right = 10,
selectInput('var1', 'Select the area you wish to view', choices = c("choose" = "","police","Medical")),
selectInput('var2', 'Select the area you would like to view' ,choices =c("choose" = "")),
))
server <- function(input, output, session){
output$map <- renderLeaflet({
leaflet(map1) %>% addTiles() %>%
fitBounds(~min(long), ~min(lat), ~max(long), ~max(lat))
})
observe({
a_option <- input$var1
if (a_option == "police") {
updateSelectInput(session, "var2", choices = c("choose" = "",pollist$row1))
}else{
updateSelectInput(session, "var2", choices = c("choose" = "",medlist$row1))
}
})
observe({
catreq <- input$var1
#mapfilt <- input$var2
mydf<- input$var1
if (mydf == "police") {
mydf = poldat
}else{
mydf = meddat
}
mycol <- input$var1
if (mycol == "police") {
mycol = "fallswithin"
}else{
mycol = "healtharea"
}
map1 <- subset(mydf, mycol == input$var2)
leafletProxy("map", data = map1[2:3]) %>% addTiles()# %>%
addMarkers(clusterOptions = markerClusterOptions(),label = paste("test"))
})
}
shinyApp(ui, server)

ggvis and shiny: add_tooltip displays wrong info when there are several ggvis plots with add_tooltip in one shiny app

I just find a weird situation that add_tooltip displays wrong info when there are several ggvis plots with add_tooltip in one shiny app. Actually the order/item shown by add_tooltip in first ggvis is correct, but are wrong in the second or third ggvis plot. At the bottom is a simple version example with mtcars. Any suggestion?
Thanks a lot,
Ying
ui.R for add_tooltip_test
library(shiny)
library(ggvis)
shinyUI(fluidPage(
h5("add_tooltip test"),
sidebarLayout(
sidebarPanel(
checkboxInput(inputId="byVS", label="Selet vs value", value = FALSE),
conditionalPanel(
condition = "input.byVS == true",
selectizeInput(
inputId = "VS",
label = "Select a value",
multiple = FALSE,
choices = c(0,1),
selected=c(0)
)
),
checkboxInput(inputId="byAM", label="Selet am value", value = FALSE),
conditionalPanel(
condition = "input.byAM == true",
selectizeInput(
inputId = "AM",
label = "Select a value",
multiple = FALSE,
choices = c(0,1),
selected=c(0)
)
)
),
mainPanel(
uiOutput("plot1_ui"),
ggvisOutput("plot1")
)
)
))
server.R for add_tooltip_test
library(shiny)
library(ggvis)
library(dplyr)
shinyServer(function(input, output, session) {
vis <- reactive({
if(input$byVS == FALSE && input$byAM == FALSE){
myplotdata <- mutate(mtcars, carName=rownames(mtcars), id=1:nrow(mtcars))
my_values <- function(x) {
if(is.null(x)) return(NULL)
row <- myplotdata[myplotdata$id == x$id, ]
row$carName
}
myplotdata %>%
ggvis(x= ~hp, y= ~mpg) %>%
layer_points(key := ~id, fill = ~factor(cyl)) %>%
add_tooltip(my_values,"hover") %>%
group_by(cyl) %>%
layer_model_predictions(model = "lm", strokeDash = ~factor(cyl))
}else if(input$byVS == FALSE && input$byAM == TRUE){
amplotdata <- subset(mtcars, am == input$AM)
amplotdata <- mutate(amplotdata, carName=rownames(amplotdata), id=1:nrow(amplotdata))
am_values <- function(x) {
if(is.null(x)) return(NULL)
row <- amplotdata[amplotdata$id == x$id, ]
row$carName
}
amplotdata %>%
ggvis(x= ~hp, y= ~mpg) %>%
layer_points(key := ~id, fill = ~factor(cyl)) %>%
add_tooltip(am_values,"hover") %>%
group_by(cyl) %>%
layer_model_predictions(model = "lm", strokeDash = ~factor(cyl))
}else if(input$byVS == TRUE){
vsplotdata <- subset(mtcars, vs == input$VS)
vsplotdata <- mutate(vsplotdata, carName=rownames(vsplotdata), id=1:nrow(vsplotdata))
vs_values <- function(x) {
if(is.null(x)) return(NULL)
row <- vsplotdata[vsplotdata$id == x$id, ]
row$carName
}
vsplotdata %>%
ggvis(x= ~hp, y= ~mpg) %>%
layer_points(key := ~id, fill = ~factor(cyl)) %>%
add_tooltip(vs_values,"hover") %>%
group_by(cyl) %>%
layer_model_predictions(model = "lm", strokeDash = ~factor(cyl))
}
})
vis %>% bind_shiny("plot1", "plot1_ui")
})