I have created a large number of data tables using mapply, however, I need to access the data tables in a following step. R assigns random IDs to these tables if the user does not specify the IDs. Here is an example of what I would like to do:
library(shiny)
ui <- fluidPage(
h2("Last clicked:"),
verbatimTextOutput("last_clicked"),
actionButton("reset", "Reset clicked value"),
h2("Datatable:"),
DT::dataTableOutput("dt")
)
server <- function(input, output) {
# the last clicke value
output$last_clicked <- renderPrint({
str(last())
})
output$dt <- DT::renderDataTable({
DT::datatable(head(mtcars, 2), elementId = "DT_Test")
})
observeEvent(input$dt_cell_clicked, {
validate(need(length(input$dt_cell_clicked) > 0, ''))
print("You clicked something!")
})
myProxy = DT::dataTableProxy('dt')
last = reactiveVal(NULL)
observe({
last(input$dt_cell_clicked)
})
observeEvent(input$reset, {
DT::selectRows(myProxy, NULL)
last(NULL)
output$dt <- DT::renderDataTable({
DT::datatable(head(mtcars, 2))
})
})
}
shinyApp(ui, server)
If I look at the html, the elementID did not change to what I wanted, in fact, R gives the warning:
Warning in origRenderFunc() :
Ignoring explicitly provided widget ID "DT_Test"; Shiny doesn't use them
Even after the call, still not sure what you are trying to do.
But if you have a list of datatables and you want to access them, it works rather well like this:
library(shiny)
library(purrr)
ui <- fluidPage(
h2("Last clicked:"),
verbatimTextOutput("last_clicked"),
h2("elementId values"),
verbatimTextOutput("elementId_values"),
actionButton("reset", "Reset clicked value"),
h2("Datatable:"),
DT::dataTableOutput("dt")
)
server <- function(input, output) {
# the last clicke value
output$last_clicked <- renderPrint({
str(last())
})
table <- DT::datatable(head(mtcars, 2), elementId = "DT_Test")
table2 <- DT::datatable(tail(mtcars, 1), elementId = "DT_Test2")
list_of_data_tables <- list(table, table2)
element_ids <- purrr::map(list_of_data_tables, "elementId")
output$elementId_values <- renderPrint({
element_ids
})
output$dt <- DT::renderDataTable({
list_of_data_tables[[which(element_ids == "DT_Test2")]]
})
observeEvent(input$dt_cell_clicked, {
validate(need(length(input$dt_cell_clicked) > 0, ''))
print("You clicked something!")
})
myProxy = DT::dataTableProxy('dt')
last = reactiveVal(NULL)
observe({
last(input$dt_cell_clicked)
})
observeEvent(input$reset, {
DT::selectRows(myProxy, NULL)
last(NULL)
output$dt <- DT::renderDataTable({
DT::datatable(head(mtcars, 2))
})
})
}
shinyApp(ui, server)
Related
In the below code for a Shiny app, I am expecting the print line to execute when the user clicks on a new row in the datatable. When I do this, the textOutput updates with the selected row via input$table_rows_selected as expected. But why does change <- reactive({ }) not take a dependency on changes to input$table_rows_selected and trigger the print message?
I see that it works with observe({}) but ultimately I want to use a value that reactive returns in different places (e.g here return and return2).
library(shiny)
library(DT)
ui <- fluidPage(
DT::DTOutput("table"),
textOutput("selected"),
textOutput("return"),
textOutput("return2")
)
server <- function(input, output) {
output$table <- DT::renderDataTable({
data.frame(a = 1:3, b = 4:6)
}, selection = 'single')
output$selected <- renderText({
input$table_rows_selected
})
change <- reactive({
input$table_rows_selected
print("it changed!")
"return"
})
output$return <- renderText({
isolate(change())
})
output$return2 <- renderText({
paste0(isolate(change()), "_2")
})
}
# Run the application
shinyApp(ui = ui, server = server)
Your code has 2 problems:
a reactive is just a function, therefore its return value is the last value generated in the reactive -> you need to put input$table_rows_selected last
the isolate(change()) means that reactives don't have a dependency on input$table_rows_selected -> remove the isolate
library(shiny)
library(DT)
ui <- fluidPage(
DT::DTOutput("table"),
textOutput("selected"),
textOutput("return"),
textOutput("return2")
)
server <- function(input, output) {
output$table <- DT::renderDataTable({
data.frame(a = 1:3, b = 4:6)
}, selection = 'single')
output$selected <- renderText({
input$table_rows_selected
})
change <- reactive({
print("it changed!")
input$table_rows_selected
})
output$return <- renderText({
change()
})
output$return2 <- renderText({
paste0(change(), "_2")
})
}
# Run the application
shinyApp(ui = ui, server = server)
I'm making an app in which the user can create as many tables as he/she wants and display the code necessary to remake each individual table using shinymeta. I can generate the code for each of these tables but I have a problem when I want to create a complete modal that shows every code for each table.
To be clearer, here's a reproducible example:
library(shiny)
library(dplyr)
library(shinymeta)
module_ui <- function(id){
ns <- NS(id)
tagList(
fluidRow(
actionButton(ns("show_table"), "Show table"),
actionButton(ns("show_code"), "Show code"),
tableOutput(ns("table"))
)
)
}
module_server <- function(input, output, session){
data <- metaReactive2({
req(input$show_table)
isolate(metaExpr({
mtcars
}))
})
data2 <- metaReactive({
..(data()) %>%
select(mpg)
})
output$table <- renderTable({
data2()
})
observeEvent(input$show_code, {
showModal(modalDialog(
renderPrint({
expandChain(data(), data2())
})
))
})
return(data())
}
ui <- fluidPage(
actionButton("launch", "Launch"),
actionButton("show_full_code", "Show the full code (at least 2 'launch' before)")
)
server <- function(input, output, session) {
count <- reactiveValues(value = 0)
observeEvent(input$launch, {
count$value <- count$value + 1
insertUI(selector = "#show_full_code",
where = "afterEnd",
ui = module_ui(paste0("x", count$value)))
callModule(module_server, paste0("x", count$value))
})
#### "Merge" the single code modals in one big
observeEvent(input$show_full_code, {
showModal(modalDialog(
renderPrint({
expandChain(x1_data)
})
))
})
}
shinyApp(ui, server)
When you click on "Launch", two buttons are generated and you can display a table ("Show table") and the code to remake this table ("Show code"). You can click on "Launch" indefinitely and the table will be named x1_data, x2_data, etc.
However, when I try to generate the code that unites every individual code (by clicking on "Show the full code"), x1_data is not found. Using x1_data() does not work either. I'm not a fan of asking two questions in one post but I will do this now:
How can I access the reactive elements created inside modules?
How can I "merge" every individual code in a big one?
Also asked on RStudio Community
Edit: following a comment, I add a second reactive expression in my example, so that I can't use return on both of them.
Ok, I came up with an answer that has the module return the expandChain() results rather than trying to render them again in the server:
library(shiny)
library(dplyr)
library(shinymeta)
module_ui <- function(id){
ns <- NS(id)
tagList(
fluidRow(
actionButton(ns("show_table"), "Show table"),
actionButton(ns("show_code"), "Show code"),
tableOutput(ns("table"))
)
)
}
module_server <- function(input, output, session){
data <- metaReactive2({
req(input$show_table)
isolate(metaExpr({
mtcars
}))
})
data2 <- metaReactive({
..(data()) %>%
select(mpg)
})
output$table <- renderTable({
data2()
})
observeEvent(input$show_code, {
showModal(modalDialog(
renderPrint({
expandChain(data(), data2())
})
))
})
########################################
### create list of reactive objects ####
########################################
return(list(
expandChain(data(), data2())
)
)
}
ui <- fluidPage(
actionButton("launch", "Launch"),
actionButton("show_full_code", "Show the full code (at least 2 'launch' before)")
)
server <- function(input, output, session) {
count <- reactiveValues(value = 0)
observeEvent(input$launch, {
count$value <- count$value + 1
insertUI(selector = "#show_full_code",
where = "afterEnd",
ui = module_ui(paste0("x", count$value)))
callModule(module_server, paste0("x", count$value))
})
#### "Merge" the single code modals in one big list object
my_data <- reactive({
req(count$value)
my_set <- 1:count$value
### lapply through the different name spaces so all are captured ###
final <- lapply(my_set, function(x){
temp <- callModule(module_server, paste0("x", x))
return(temp)
})
return(final)
})
#### "Merge" the single code modals in one big
observeEvent(input$show_full_code, {
showModal(modalDialog(
renderPrint({
temp <- sapply(unlist(my_data()), function(x){
print(x)
})
})
))
})
}
shinyApp(ui, server)
What I want to do is to make the output from the for loop run available for many render outputs in Shiny App.
I created the simple example of my problem.
There is the same for loop in each renderPrint() function.
Can I code that in such a way that the for loop is moved outside render*() functions?
I've found examples how to use reactives in loops but haven't found a solution to the reversed task.
Thank you for your help and attention.
library(shiny)
ui <- fluidPage(sidebarLayout(
sidebarPanel(
numericInput(
inputId = "seed",
label = "Set seed:",
value = 1
),
numericInput(
inputId = "Number",
label = "Number:",
value = 1,
min = 1,
step = 1
)
),
mainPanel(
verbatimTextOutput("summary"),
dataTableOutput("table"),
verbatimTextOutput("data")
)
))
server <- function(input, output) {
a <- reactive({
set.seed(input$seed)
rnorm(input$Number, 2, 1)
})
b <- reactive({
5 * a()
})
rn <- reactive({
c(1:input$Number)
})
fun <- function(x, y) {
x + y
}
Table <- reactive({
data.frame(rn = rn(),
a = a(),
b = b())
})
output$table <- renderDataTable({
Table()
})
output$summary <- renderPrint({
for (i in Table()$rn) {
print (fun(Table()$a[i], Table()$b[i]))
}
})
output$data <- renderPrint({
for (i in Table()$rn) {
print (fun(Table()$a[i], Table()$b[i]))
}
})
}
shinyApp(ui = ui, server = server)
Extract the for loop into a function. You can use reactive values in functions with no problem, as long as you're not calling the function outside a reactive context (render*, reactive, observe).
Example:
printTable <- function() {
for (i in Table()$rn) {
print (fun(Table()$a[i], Table()$b[i]))
}
}
output$summary <- renderPrint({
printTable()
})
output$data <- renderPrint({
printTable()
})
or more efficiently, you could capture the print output as a string and just re-use it:
capturedTableString <- reactive({
capture.output({
for (i in Table()$rn) {
print (fun(Table()$a[i], Table()$b[i]))
}
})
})
printTable <- function() {
cat(capturedTableString(), sep = "\n")
}
output$summary <- renderPrint({
printTable()
})
I want to make my rhandsontable read only on clicking the action button 'Freeze Forecast' and activate the table on clicking on 'Edit Forecast'. It should show me the Sum Output on clicking on 'Generate Forecast' button.
Please help to correct my existing code as per above conditions.
UI.R
packages <- c( "shiny", "data.table", "devtools", "shinysky","googleVis","scales","rhandsontable" )
lapply( packages, require, character.only = TRUE )
jsResetCode <- "shinyjs.reset = function() {history.go(0)}" #JS Code to refresh the App
did_recalc <- FALSE
ui <- fluidPage(
# Application title
titlePanel("Scenario Planner Test App"),
br(),br(),
actionButton("recalc", "Generate Forecast"),
actionButton("edit", "Edit Forecast"),
actionButton("freeze", "Freeze Forecast"),br(),br(),
rHandsontableOutput('table'),br(),br(),
textOutput('restitle'),
textOutput('result')
)
Server.R
Sys.setenv(R_ZIPCMD="/usr/bin/zip")
packages <- c( "shiny", "data.table", "devtools", "shinysky","googleVis","scales","reshape2" )
lapply( packages, require, character.only = TRUE )
disableActionButton <- function(id,session) {
session$sendCustomMessage(type="jsCode1",
list(code= paste("$('#",id,"').prop('disabled',true)"
,sep="")))
}
enableActionButton <- function(id,session) {
session$sendCustomMessage(type="jsCode2",
list(code= paste("$('#",id,"').prop('disabled',false)"
,sep="")))
}
shiny::shinyServer( function(input,output,session)({
values <- reactiveValues(data=as.data.frame(runif(2)))
observe({
input$recalc
values$data <- as.data.frame(runif(2))
})
observe({
if(!is.null(input$table))
values$data <- hot_to_r(input$table)
})
output$table <- renderRHandsontable({
rhandsontable(values$data)
})
observe({
input$freeze
print("freeze")
##if(!is.null(input$table))
print("2freeze")
rhandsontable(values$data) %>%
hot_table(readOnly = TRUE)
})
output$restitle <- renderText({
"Sum Output"
})
output$result <- renderText({
sum(values$data)
})
})
)
I got this to work by
Adding a state variable to your reactive called readonly
Adding two observerEvent routines to the edit and freeze action buttions to toggle readonly.
Modifying your output$table command to use the reactive readonly variable.
It would have been easier, and not needed a lot of those elements if you had just used a checkbox to indicate that the table is editable, and then wired that variable to the readOnly parameter, but sometimes you need to do it this way, so I solved it like this.
The complete server.R code is here:
packages <- c("shiny","data.table","devtools","shinysky","googleVis","scales","reshape2")
lapply(packages,require,character.only = TRUE)
disableActionButton <- function(id,session) {
session$sendCustomMessage(type = "jsCode1",
list(code = paste("$('#",id,"').prop('disabled',true)"
,sep = "")))
}
enableActionButton <- function(id,session) {
session$sendCustomMessage(type = "jsCode2",
list(code = paste("$('#",id,"').prop('disabled',false)"
,sep = "")))
}
shiny::shinyServer(function(input,output,session)({
values <- reactiveValues(data = as.data.frame(runif(2)),readonly=FALSE)
observe({
input$recalc
values$data <- as.data.frame(runif(2))
})
observe({
if (!is.null(input$table))
values$data <- hot_to_r(input$table)
})
output$table <- renderRHandsontable({
rhandsontable(values$data,readOnly=values$readonly)
})
observeEvent(input$edit, {
values$readonly <- FALSE
})
observeEvent(input$freeze,{
values$readonly <- TRUE
})
output$restitle <- renderText({
"Sum Output"
})
output$result <- renderText({
sum(values$data)
})
})
)
and it looks like this:
I have a R Shiny app that contains checkboxGroupInput, and I'm trying to create a "select all" button, using updateCheckboxGroupInput function.
You can see the full code below, but basically I defined the cb groups like this:
checkboxGroupInput("campaigns","Choose campaign(s):",campaigns_list)
and then, on a button click, call the function:
updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
I have an indication that the function ran, but what it does is actually UNselecting the checkboxes.
BTW, when I put the selected upon defining the cbGroupInput it did worked, but not on the function.
Thanks!
this is my server.R:
library(shiny)
source('usefulFunctions.R')
shinyServer(function(input, output, session) {
output$cascading <- renderUI({
provider_id <- input$provider
if (provider_id == "") return(NULL)
campaigns_list <<- t(getCampaigns(provider_id))
tagList(
checkboxGroupInput("campaigns","Choose campaign(s):",
choices = campaigns_list, selected = campaigns_list),
actionLink("selectall","Select All")
)
})
observe({
if(is.null(input$selectall)) return(NULL)
if (input$selectall > 0)
{
print(campaigns_list)
updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
}
})
})
I also added the select and unselect options here by checking if the button or link are divisible by 2
#rm(list = ls())
library(shiny)
campaigns_list <- letters[1:10]
ui =fluidPage(
checkboxGroupInput("campaigns","Choose campaign(s):",campaigns_list),
actionLink("selectall","Select All")
)
server = function(input, output, session) {
observe({
if(input$selectall == 0) return(NULL)
else if (input$selectall%%2 == 0)
{
updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list)
}
else
{
updateCheckboxGroupInput(session,"campaigns","Choose campaign(s):",choices=campaigns_list,selected=campaigns_list)
}
})
}
runApp(list(ui = ui, server = server))
If campaigns_list is a list, might be because you are specifying the list of all your choices instead of the value of the boxes that should be selected in the selected argument of your updateCheckboxGroupInput.
Try replacing selected=campaigns_list by selected=unlist(campaigns_list).
Here is an example with dummy names:
library(shiny)
server<-function(input, output,session) {
observe({
if(input$selectall == 0) return(NULL)
else if (input$selectall > 0)
{
variables<-list("Cylinders" = "cyl","Transmission" = "am","Gears" = "gear")
updateCheckboxGroupInput(session,"variable","Variable:",choices=variables,selected=unlist(variables))
}
})
}
ui <- shinyUI(fluidPage(
checkboxGroupInput("variable", "Variable:",list("Cylinders" = "cyl","Transmission" = "am","Gears" = "gear")),
actionButton("selectall", "Select All")
))
shinyApp(ui = ui, server = server)