Using embedded do.call() in Shiny - shiny

I'm trying to use Shiny + ShinyBS to create a collapsible panel whitch contains a bunch of column values per column.
However, I'm having trouble in applying do.call correctly (or in the sequence I want).
Source code for server.R:
require(shiny)
library(lazyeval)
library(shinyBS)
l <- lapply(mtcars, function(x) unique(x))
shinyServer(function(input, output) {
output$plot <- renderUI({
col_list <- lapply(1:length(l), function(i) {
col <- l[[i]]
a <- lapply(1:min(length(col), 10), function(j) {
interp(quote(bsToggleButton(nm,lb)),
.values=list(nm = paste0(names(l)[i],
'_val_',
j),
lb = col[j]))
})
pars <- list(inputId = paste0('btng_',
names(l)[i]),
label = '', value = '', a)
interp(quote(bsCollapsePanel(names(l)[i],
fluidRow(
column(4,
do.call(bsButtonGroup,
unlist(pars))
)
),
id = nm, value = val)),
.values = list(i = i,
nm = paste0('test_',i),
val = '')
)
})
pars2 <- list(multiple = TRUE,
open = "test_1",
id = "collapse1",
col_list)
do.call(bsCollapse, unlist(pars2))
})
})
Source code for ui.R:
require(shiny)
shinyUI(
fluidPage(
uiOutput('plot')
)
)
The code can NOT run! The problem is pars seems to be static, it only contains the value of the first iteration.

Firstly, the code was still not reproducible as is. I suspect you had run parts of the provided code within your environment (e.g. the 'pars' object was not found with your provided code on my machine).
Second, I think you have just made your apply statements too complex. The idea of apply statements is to improve readability of your code as opposed to for loops. Here you have crammed so much in to the lapply statements that it is difficult to parse out anything.
To address this, I broke the components apart into their own lapply statements (which is far more approachable now). What was happening with your previous code is that your pars object was taking all the variables from the a object. Once these components were separated, I could easily just alter the pars statement to iterate through each a element. This provides the different values for each iteration (i.e. variable). I have only included the server.R as there is not changes to your ui.R
As a followup to your comments below, you are correct that the interp and quote arguments are unnecessary (I generally avoid them again for clarity, my personal preference). As for best practices, I sum it up in one concept 'clarity then performance'. If you are unsure about your objects then LOOK AT THEM! Below you will find an updated server.R file. I have also minimally commented it. You will also find an example of accessing the bsGroupButton values. You can see it is the group id that you must reference. This should get you started (be sure to add tableOutput('result') to your ui.R. I highly recommend you look into the documentation of ShinyBS or at least the demo page.
Concise and annotated server.R
require(shiny)
library(shinyBS)
l <- lapply(mtcars,function(x)unique(x))
shinyServer(function(input, output) {
output$plot <- renderUI({
# Create your buttons
a <- lapply(1:length(l), function(i){
col <- l[[i]]
lapply(1:min(length(col),10), function(j){
bsButton(paste0(names(l)[i], '_val_', j), label=col[j], value=col[j])
})
})
# add the additional arguments for your future bsButtonGroup call
pars <- lapply(1:length(l), function(i) {
list(inputId =paste0('btng_',names(l)[i]), label = '', value = '',a[[i]])
})
col_list<-lapply(1:length(l), function(i) {
# separate the components for clarity
rawButtons <- unlist(pars[i], recursive=F)
buttons <- do.call(bsButtonGroup, c(rawButtons[[4]], inputId=rawButtons$inputId))
# collapse the groups into panels
bsCollapsePanel(title=names(l)[i],
buttons, id=paste0('test_',i), value='')
})
# Collapse everything, no need for pars2, just add elements in a vector
do.call(bsCollapse, c(col_list, multiple=TRUE, open="test_1", id="collapse1"))
})
output$result<- renderTable({
df <- cbind(c("mpg toggle button", c(deparse(input$btng_mpg))))
return(df)
})
})
original answer for server.R
require(shiny)
library(shinyBS)
require(lazyeval)
l <- lapply(mtcars,function(x)unique(x))
shinyServer(function(input, output) {
output$plot <- renderUI({
a <- lapply(1:length(l), function(i) {
col <- l[[i]]
lapply(1:min(length(col),10), function(j) {
interp(
quote(bsToggleButton(nm,lb))
,.values=list(nm=paste0(names(l)[i],'_val_', j),lb=col[j]))
})
})
pars <- lapply(1:length(l), function(i) {
list(inputId =paste0('btng_',names(l)[i]), label = '', value = '',a[[i]])
})
col_list<-lapply(1:length(l), function(i) {
interp(
quote(
bsCollapsePanel(names(l)[i],
fluidRow(
column(4,
do.call(bsButtonGroup,unlist(pars[i]))
)
),
id=nm,value=val))
,.values=list(i=i,nm=paste0('test_',i),val='')
)
})
pars2 <- list(multiple = TRUE, open = "test_1", id = "collapse1",col_list)
do.call(bsCollapse,unlist(pars2))
})
})

Related

echarts4r mark line with proxy chart

Is it possible to add and remove a mark line using a proxy so that the chart doesn't get fully redrawn?
To illustrate what it would look like:
library(shiny)
library(echarts4r)
df <- data.frame(
x = 1:100,
y = runif(100)
)
ui <- fluidPage(
actionButton("add", "Add series"),
actionButton("rm", "Remove series"),
echarts4rOutput("chart")
)
server <- function(input, output){
output$chart <- renderEcharts4r({
e_charts(df, x) %>%
e_scatter(y, z)
})
# e_mark_line() - has id added for this example
observeEvent(input$add, {
echarts4rProxy("chart", data = df, x = x) %>%
e_mark_line(
id = "my_line"
, data = list(xAxis = 50)
, title = "Line at 50") %>%
e_execute()
})
# e_remove_mark_line() - is made up for this example
observeEvent(input$rm, {
echarts4rProxy("chart") %>%
e_remove_mark_line("my_line")
})
}
shinyApp(ui, server)
It's a bit odd. Apparently, a 'mark line' is attached to a specific series. I didn't add handlers for the id field, it can be done, though. However, you would also have to specify the trace it's attached to.
BTW: in your code, you wrote e_scatter(y, z), but there is no z.
The easiest method is to create a function like the one you eluded to in your code.
There are two custom functions. One for Shiny in R code. One for the browser in Javascript. Combined, these create the function e_remove_markLine_p.
The R function (specifically for Shiny applications)
e_remove_markLine_p <- function (proxy)
{
opts <- list(id = proxy$id)
proxy$session$sendCustomMessage("e_remove_markLine_p", opts)
return(proxy)
}
The JS function
Shiny.addCustomMessageHandler('e_remove_markLine_p',
function(data) {
var chart = get_e_charts(data.id);
let opts = chart.getOption();
if(opts.markLine.length > 0) {
opts.markLine.length = 0; /* remove data */
}
chart.setOption(opts, true);
})
Using the power of Shiny, these two functions carry the request from the browser to R & back to the browser.
In the code, I've changed a few other things. Instead of e_mark_line, I used e_mark_p. I'm not sure if it matters, but per the documentation, that's the appropriate function.
Here's the entire app altogether.
library(tidyverse)
library(echarts4r)
library(shiny)
set.seed(315)
df <- data.frame(x = 1:100, y = runif(100))
# custom function for 'e_remove_markLine_p',
e_remove_markLine_p <- function (proxy)
{
opts <- list(id = proxy$id)
proxy$session$sendCustomMessage("e_remove_markLine_p", opts)
return(proxy)
}
ui <- fluidPage(
# adds the same call to both add and remove buttons
tags$head(
tags$script(HTML("
Shiny.addCustomMessageHandler('e_remove_markLine_p',
function(data) {
var chart = get_e_charts(data.id);
let opts = chart.getOption();
if(opts.markLine.length > 0) {
opts.markLine.length = 0; /* remove data */
}
chart.setOption(opts, true);
})
"))),
actionButton("add", "Add series"),
actionButton("rm", "Remove series"),
echarts4rOutput("chart")
)
server <- function(input, output){
output$chart <- renderEcharts4r({
e_charts(df, x) %>%
e_scatter(y) # <--- I removed z, since it doesn't exist...
})
observeEvent(input$add, {
echarts4rProxy("chart", data = df, x = x) %>%
e_mark_p(type = "line",
data = list(xAxis = 50),
title = "Line at 50") %>%
e_merge() %>% e_execute() # merge when adding to the plot
})
observeEvent(input$rm, {
echarts4rProxy("chart") %>%
e_remove_markLine_p() # remove all "mark" lines
})
}
shinyApp(ui, server) # show me what you got

Is there a good way to merge data based on a drop down menu in R?

I have been trying to merge data with another data set based on input from a drop down. I have just started learning R and have run into some problems and want to know if there is a better way of going about this.
I am getting an error that it cannot coerce class c(ReactiveExpr, reactive) to a data frame.
library(shiny)
library(plyr)
library(dplyr)
library(xlsx)
server <- function(input, output){
annotation1 <- read.xlsx("input1.xlsx", sheetIndex = 1, header = TRUE)
annotation2 <- read.xlsx("input2.xlsx", sheetIndex = 1, header = TRUE)
data_input <- eventReactive(input$userfile, {
df <- read.xlsx(input$userfile$datapath, sheetIndex = 1, header = TRUE)
})
output$data_input <- renderTable(data_input())
output$annotation <- renderTable(annotation)
data_species <- c("Set1", "Set2")
# Drop-down selection box for which data set
output$choose_species <- renderUI ({
selectInput("species", "Species", as.list(data_species))
})
output$mergeddata <- renderTable({
if(input$species == "Set1"){
eventReactive("Set1",({left_join(data_input(), annotation1, by = c("Column1" = "Column1"))}))
}
else if(input$species == "Set2"){
eventReactive("Set2",({left_join(data_input(), annotation2, by = c("Column1" = "Column1"))}))
}
})
}
ui <- fluidPage(
titlePanel(
div("Test")
),
sidebarLayout(
sidebarPanel(
fileInput("userfile", "Input File", multiple =FALSE,
buttonLabel = "Browse Files", placeholder = "Select File"),
uiOutput("choose_species"),
uiOutput("choose_annotations"),
),
mainPanel(
tableOutput("mergeddata"),
br()
),
),
)
# Run the application
shinyApp(ui = ui, server = server)
In general, you approach seems ok. The error you get is from the line
eventReactive("Set1",({left_join(data_input(), annotation1, by = c("Column1" = "Column1"))}))
An eventReactive returns an (unevaluated) reactive expression which you try to render as data.frame with renderTable. To circumvent this, you could use:
eventReactive("Set1",({left_join(data_input(), annotation1, by = c("Column1" = "Column1"))}))()
However, here you don't need eventReactive, because your reactivity comes from input$species (you want to change the table output based on this input). Therefore, you can just use:
output$mergeddata <- renderTable({
if(input$species == "Set1"){
merge_data <- annotation1
} else {
merge_data <- annotation2
}
left_join(data_input(), merge_data, by = c("Column1"))
})

Shiny - Updating global variable and seeing the result in current session

I am working with global variables that update after time X. This issue I am coming across is it updates the global variable but the current session doesn't update accordingly, however, any new session open uses the updated global variable.
Question: how do I get the current session to use the updated global variable? I thought wrapping it in a reactive would work but it doesn't.
Code:
library(shiny)
library(shinydashboard)
####/GLOBAL/####
num <- 4
####/UI/####
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(
verbatimTextOutput("test")
)
ui <- dashboardPage(header, sidebar, body)
####/SERVER/####
server <- function(input, output, session) {
data <- reactive({num})
output$test <- renderText({ data() })
observe({
invalidateLater(0.5*60*1000,session)
num <<- sample(1:1000,1,replace=T)
})
}
shinyApp(ui, server)
If you wait 30+ seconds and then open up a new session you will see that the number has changed from 4 but the original session still shows 4. They should be showing the same number.
Solved! Realized I needed to wrap it in a reactiveValues versus reactive. I also made the updating a value a dataframe versus a single number because that fits my real dashboard's problem.
library(shiny)
library(shinydashboard)
####/GLOBAL/####
dataset <- data.frame(ColA = c("dogs", "cats", "birds"), ColB = c(10, 2, 2), stringsAsFactors = FALSE)
####/UI/####
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(
box(width = 3, tableOutput("test"))
)
ui <- dashboardPage(header, sidebar, body)
####/SERVER/####
server <- function(input, output, session) {
values <- reactiveValues(n = dataset)
data <- reactive({values$n})
output$test <- renderTable({ data() })
observe({
invalidateLater(0.5*60*1000,session)
new1 <- sample(1:10,1,replace=T)
new2 <- sample(1:10,1,replace=T)
new3 <- sample(1:10,1,replace=T)
print(new1)
print(new2)
print(new3)
dat <- data.frame(ColA = c("dogs", "cats", "birds"), ColB = c(new1, new2, new3), stringsAsFactors = FALSE)
values$n <- dat
dataset <<- dat
})
}
shinyApp(ui, server)

Interactive Regression Model not outputting model summary

I am attempting to run a regression that allows users to determine regression inputs, and then provide an output that is the regression summary. For whatever reason, the output is not coming out correct, and I have looked everyone on the internet to find a solution. I am hoping somebody can help.
For clarification, this is in shiny.
Here is my server code:
shinyServer(
function(input,output,session) {
mod <- eventReactive(input$analysis,{
response <- data[,2]
explan1 <- data[,input$Explan1]
explan2 <- data[,input$Explan2]
explan3 <- data[,input$Explan3]
mod1 <- lm(response~explan1+explan2+explan3)
} )
output$modelSummary <- renderPrint({
(summary(mod()$mod1))
})
output$ColumnNames <- renderPrint({
as.data.frame(colnames(data))
})
}
)
summary(model)
And my ui code
shinyUI(
fluidPage(
titlePanel("What does it take for a Hockey Team to Win?"),
titlePanel("Please select the column numbers for three variables to regress on"),
sidebarLayout(
sidebarPanel(
verbatimTextOutput("ColumnNames"),
numericInput("Explan1","Explanatory Variable 1",3,min = 3, max = 13),
numericInput("Explan2","Explanatory Variable 2",4,min = 3,max = 13),
numericInput("Explan3","Explanatory Variable 3",5,min = 3, max = 13)
),
mainPanel(
actionButton("analysis","Analyze!"),
verbatimTextOutput("modelSummary")
)
)
)
)
When I run the app, select the input columns (which are by number rather than name. I hope to fix this later) and click analyze, I get the following output:
Length Class Mode
0 NULL NULL
I haven't been able to find much relevant information on this output. I hope you all can help.
Thank you in advance.
You're just calling the reactive incorrectly, it should be: summary(mod()) instead of summary(mod()$mod1). Reactives behave very much like functions the way that they return objects.
Here is a fully reproducible example, with an example on how to use a formula instead of individually selecting the columns:
col_names <- names(mtcars)
ui <- fluidPage(
sidebarPanel(
verbatimTextOutput("ColumnNames"),
selectInput("Response", "Response Variable", choices = col_names, selected = "mpg"),
selectInput("Explan1","Explanatory Variable 1", choices = col_names, selected = "cyl"),
selectInput("Explan2","Explanatory Variable 2", choices = col_names, selected = "disp"),
selectInput("Explan3","Explanatory Variable 3", choices = col_names, selected = "wt")
),
mainPanel(
actionButton("analysis","Analyze!"),
verbatimTextOutput("modelFormula"),
verbatimTextOutput("modelSummary")
)
)
server <- function(input, output, session) {
myformula <- reactive({
expln <- paste(c(input$Explan1, input$Explan2, input$Explan3), collapse = "+")
as.formula(paste(input$Response, " ~ ", expln))
})
mod <- eventReactive(input$analysis, {
lm(myformula(), data = mtcars)
})
output$modelFormula <- renderPrint({
myformula()
})
output$modelSummary <- renderPrint({
summary(mod())
})
}
shinyApp(ui, server)
Screenshot:

Downloading the output from Shiny APP (need some advice)

I want to download the output of this App which I made but there is an error and when I open the downloaded data it is empty.I make a data set by output$other_val_show and I want to download it. Any advice?
The following code in for the UI section.
library(shiny)
library(quantreg)
library(quantregGrowth)
library(plotly)
library(rsconnect)
library(ggplot2)
library(lattice)
ui = tagList(
tags$head(tags$style(HTML("body{ background: aliceblue; }"))),
navbarPage(title="",
tabPanel("Data Import",
sidebarLayout(sidebarPanel( fileInput("file","Upload your CSV",multiple = FALSE),
tags$hr(),
h5(helpText("Select the read.table parameters below")),
checkboxInput(inputId = 'header', label = 'Header', value = FALSE),
checkboxInput(inputId = "stringAsFactors", "StringAsFactors", FALSE),
radioButtons (inputId = 'sep', label = 'Separator',
choices = c(Comma=',',Semicolon=';',Tab='\t', Space=''), selected = ',')
),
mainPanel(uiOutput("tb1"))
)),
tabPanel("Interval",
sidebarLayout(sidebarPanel(
uiOutput("model_select"),
uiOutput("var1_select"),
uiOutput("rest_var_select"),
#uiOutput("testText1"), br(),
#textInput("Smooting Parameter min value", "Smooting Parameter max value", value = "")
sliderInput("range", "Smooth Parameter range:",min = 0, max = 1000, value = c(0,100)),
downloadButton('downloadData', 'Download')
),
mainPanel(helpText("Selected variables and Fitted values"),
verbatimTextOutput("other_val_show")))),
tabPanel("Model Summary", verbatimTextOutput("summary")),
tabPanel("Scatterplot", plotOutput("scatterplot"))#, # Plot
#tabPanel("Distribution", # Plots of distributions
#fluidRow(
#column(6, plotOutput("distribution1")),
#column(6, plotOutput("distribution2")))
#)
,inverse = TRUE,position="static-top",theme ="bootstrap.css"))
The following code in for the Server section. (I want to download the output which is "gr" and I want to download it by downloadHandler function.
server<-function(input,output) {
data <- reactive({
lower <- input$range[1]
upper <- input$range[2]
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)
})
output$table <- renderTable({
if(is.null(data())){return ()}
data()
})
output$tb1 <- renderUI({
tableOutput("table")
})
#output$model_select<-renderUI({
#selectInput("modelselect","Select Algo",choices = c("Reference Interval"="Model"))
#})
output$var1_select<-renderUI({
selectInput("ind_var_select","Select Independent Variable", choices =as.list(names(data())),multiple = FALSE)
})
output$rest_var_select<-renderUI({
checkboxGroupInput("other_var_select","Select Dependent Variable",choices =as.list(names(data()))) #Select other Var
})
output$other_val_show<-renderPrint({
input$other_var_select
input$ind_var_select
f<-data()
lower <- input$range[1]
upper <- input$range[2]
library(caret)
library(quantregGrowth)
dep_vars <- paste0(input$ind_var_select, collapse = "+")
after_tilde <- paste0("ps(", dep_vars, ", lambda = seq(",lower,",",upper,",l=100))")
dyn_string <- paste0(input$other_var_select, " ~ ", after_tilde)
Model<-quantregGrowth::gcrq(as.formula(dyn_string),tau=c(0.025,0.975), data=f)
temp <- data.frame(Model$fitted)
gr <- cbind(f, temp)
print(gr)
})
output$downloadData <- downloadHandler(
write.csv(gr, file, row.names = FALSE)
)
}
shinyApp(ui=ui,server=server)
It's hard to fully answer this without a minimal reproducibile example, but here's what I would try:
Create gr outside of renderPrint
Use gr() in downloadHandler
Rewrite downloadHandler to include content and filename arguments
Here's a minimal example with the same logic as your app, i.e. create a reactive dataframe which is both printed (renderPrint) and downloadable (downloadHandler).
library(shiny)
ui <- navbarPage(title = "Example",
tabPanel("First",
selectInput("fruit", "Fruit", c("apple", "orange", "pear")),
h4("Output from renderPrint:"),
textOutput("other_val_show"),
h4("Download Button: "),
downloadButton("downloadData")))
server <- function(input, output) {
gr <- reactive({
data.frame(fruit = input$fruit)
})
output$other_val_show <- renderPrint({
print(gr())
})
output$downloadData <- downloadHandler(
filename = "example.csv",
content = function(file) {
write.csv(gr(), file)
})
}
shinyApp(ui, server)
You define gr inside the scope of that renderPrint function so it isn't available to downloadHandler. You should define gr as a reactive value somewhere outside that function. That way, when you assign it in the renderPrint function, it will be accessible to the entire scope of your program.
In the future, it would be helpful to provide the text of any error messages you get - they are often quite helpful to solving problems.