Move the footer at the bottom of a DT in Shiny R - shiny

I have a datatable where the footer has "Previous/Next" text. Currently it is overlapping the "Displaying 1 of 15" text. Is there a way to move this so I dont get an over lap?
Here is a picture as well as the code. I am not very familiar with html/java script so if you could provide an answer explaining why you are using the specific code that would be greatly appreciated
library(shiny)
library(bs4Dash)
library(DT)
x = data.frame(one = rep("Hey how is everyones day? I need some help on this shiny application and learn how to use some of the features on datatable.", 10),
two = rep("this is the second column of text. ", 10),
three = rep("this is the third column of text", 10))
ui = bs4DashPage(
old_school = FALSE,
sidebar_min = TRUE,
sidebar_collapsed = FALSE,
controlbar_collapsed = FALSE,
controlbar_overlay = TRUE,
title = "Basic Dashboard",
navbar = bs4DashNavbar(),
sidebar = bs4DashSidebar(),
controlbar = bs4DashControlbar(),
footer = bs4DashFooter(),
body = bs4DashBody(
DTOutput("table")
)
)
server = function(input, output) {
output$table = renderDataTable({
datatable(x, rownames = F, style = "bootstrap", extensions = 'Responsive', options = list(
#dom = 't'
))
})
}
shinyApp(ui, server)
When i run the same code on shiny dashboard, it comes out the way I would want it to look like. So i believe it is something to do with Bs4Dash styling sheet. Below is how it looks with shinydashboard

You need to redraw your table after initialization.
$('#tableIdHere').DataTable().draw();

You can try this out , Hope it will sove your problem.
library(shiny)
library(bs4Dash)
library(DT)
x = data.frame(one = rep("Hey how is everyones day? I need some help on this shiny application and learn how to use some of the features on datatable.", 10),
two = rep("this is the second column of text. ", 10),
three = rep("this is the third column of text", 10))
ui = bs4DashPage(
old_school = FALSE,
sidebar_min = TRUE,
sidebar_collapsed = FALSE,
controlbar_collapsed = FALSE,
controlbar_overlay = TRUE,
title = "Basic Dashboard",
navbar = bs4DashNavbar(),
#sidebar = bs4DashSidebar(),
controlbar = bs4DashControlbar(),
footer = bs4DashFooter(),
body = bs4DashBody(
DTOutput("table")
)
)
server = function(input, output) {
output$table = renderDataTable({
datatable(x, rownames = F, extensions = 'Responsive', options = list(
#dom = 't'
))
})
}
shinyApp(ui, server)
I have only removed style = "bootstrap" from the renderDataTable and that serve the perpose

Your css is overwritten with some other default css. Please check if your classes are similarly named or clashing with each other.

Related

Update editable DataTable Output in RShiny

I am new to the world of RShiny and i think reactivity is bit complex to understand. I am trying to make a datatable output based on row and column condition given as per user selectinput dropdown buttons. My DataTable is editable and i want to store the updated table after user edited the cells of the datatable in a new variable but i am stuck.
I tried couple of chunks suggested on stackoverflow but none of them worked for me mostly using proxytable or reactivity. I want to store the datatable after i hit proceed button. Any help would be much appreciated.
Here is my code:
library(shiny)
library(shinyWidgets)
library(shinythemes)
library(DT)
library(data.table)
#ui
shinyApp(
ui = fluidPage(
theme = shinythemes::shinytheme("flatly"),
titlePanel("Trial"),
sidebarLayout(
shiny::sidebarPanel(
#to take multiple user input
shiny::textAreaInput(
"text_input",
label = "Write input"
),
#to slect the columns to be added
shinyWidgets::pickerInput(
inputId = "somevalue",
label = "Columns to add",
choices = colnames(df),
options = list(`actions-box` = TRUE),
multiple = TRUE
),
#action button tot show the table
shinyWidgets::actionBttn(
"show_table",
label = "Show",
size = "sm",
color = "default",
block = TRUE
), width = 2
),
mainPanel(
shiny::tabsetPanel(type = "tabs",
shiny::tabPanel("Table", DT::dataTableOutput("table")),
actionBttn("proceed","proceed")
),width = 10
)
)
),
server = function(input, output,session) {
#to add reactivity to the show button
df_filter <- reactive({
text_input <- trimws(strsplit(input$text_input, ",")[[1]])
df_filter <- df[df$make %chin% text_input, input$somevalue]
})%>% shiny::bindEvent(input$show_table)
#to output hte dt table with the filters
output$table <- DT::renderDT({
DT::datatable(df_filter(),
editable = 'cell',
options = list(scrollX = TRUE , lengthChange = FALSE, autoWidth = TRUE)
# editable = list(target = "row", disable = list(columns = c(2, 4, 5))))
)
})%>% shiny::bindEvent(df_filter())
}
)

shinyStore issue saving f7SmartSelect with multiple selection with Error in unclass(x) : cannot unclass an environment

I am trying to build a shiny app with shinyMobile, and storing the results using shinyStore, I have been looking at several answers but I haven't been able to fix this. I think there might be an issue with the multiple option.
Here is the code:
library(shiny)
library(shinyMobile)
library(shinyStore)
Species_List <- structure(list(Scientific_name = c("Juncus alpinoarticulatus ssp. nodulosus",
"Diphasiastrum complanatum ssp. complana-tum", "Rubus macrophyllus",
"Equisetum scirpoides", "Trifolium hybridum ssp. hybridum", "Narthecium ossifragum",
"Peucedanum oreoselinum", "Sonchus oleraceus", "Juncus subnodulosus",
"Minuartia viscosa"), Danish_name = c("siv, stilk-", "ulvefod, flad",
"brombær, storbladet", "padderok, tråd-", "kløver, alsike-",
"benbræk", "svovlrod, bakke-", "svinemælk, almindelig", "siv, butblomstret",
"norel, klæbrig")), row.names = c(NA, -10L), class = "data.frame")
shinyApp(
ui = f7Page(
title = "Species app",
f7SingleLayout(
navbar = f7Navbar(
title = "Select Species",
hairline = TRUE,
shadow = TRUE
),
toolbar = f7Toolbar(
position = "bottom",
f7Link(label = "Link 1", href = "https://www.google.com"),
f7Link(label = "Link 2", href = "https://www.google.com")
),
initStore("store", "shinyStore-ex1"),
# A button to save current input to local storage
actionButton("save", "Save", icon("save")),
# A button to clear the input values and local storage
actionButton("clear", "Clear", icon("stop")),
# main content
f7Shadow(
intensity = 16,
hover = TRUE,
f7SmartSelect(inputId = "SpeciesListSc",
label = "Select all species",
multiple = TRUE,
choices = unique(Species_List$Scientific_name),
virtualList = T,
openIn = "sheet")
)
)
),
server = function(input, output, session) {
observe({
if (input$save <= 0){
updateF7SmartSelect(session, inputId = "SpeciesListSc", selected = isolate(input$store)$SpeciesListSc, choices = unique(Species_List$Scientific_name), multiple = TRUE)
}
})
observe({
if (input$save > 0){
updateStore(session, name = "SpeciesListSc", isolate(input$SpeciesListSc))
}
})
}
)

Create text wrap and manage column width with Datatable in Shiny

I have a data table that has a lot of written text. I would like to organize this in an easy to read way. I have tried a few ideas but they do not seem to work. I am also open to any advice on how I should be organizing the data table.
Here is my code I am trying to control the width of the columns. Right now the width are extremely wide and i would like to narrow selected columns quite a bit.
output$newsfeed = renderDataTable({
datatable(df, rownames = F, extensions = "Scroller",
options = list(deferRender = TRUE,
scrollY = 400,
scrollX = TRUE,
scroller = TRUE,
autoWidth = TRUE,
columnDefs = list(list(width = '50px', targets = list(1,2,3,4,5)))
))
})
Thank you for your help.
Try using width = '10%' for the columns of interest.
library(DT)
library(shiny)
dat <- data.frame(
V1 = c("A", "B"),
V2 = c(
"A cool guy living in US and Canada",
"A cool guy living in New York"
),
V3 = c(
"A cool guy living in US and Canada",
"A cool guy living in New Jersey"
),
V4 = c(
"A cool guy living in US and Canada",
"A cool guy living in California"
),
V5 = c(
"A cool guy living in the US and else where",
"A cool guy living in Texas"
),
stringsAsFactors = FALSE
)
ui <- fluidPage(
DTOutput("table")
)
server <- function(input, output){
output[["table"]] <- renderDT({
datatable(dat, options = list(
deferRender = TRUE,
scrollY = 400,
scrollX = TRUE,
scroller = TRUE,
autoWidth = TRUE,
columnDefs = list(list(width = '10%', targets = c(2,3,4)))
)) # %>% formatStyle(columns = c(2,3), width='20px')
})
}
shinyApp(ui, server)
I guess 'extensions = "Scroller"' conflicts controlling column width.
When I add 'extensions = "Scroller"' to YBS's code then texts is not wrapped.

Shiny output elements not displaying in bs4Dash with nested modules

EDIT: The author of the bs4Dash package, David Granjon, recently provided an answer to the question asked in the Github issue referenced below and closed it.
My question is very likely related to this issue in bs4Dash github repo, but no answer was provided there.
The full reproducible codes are at the end of the question
My goal
I am making a modularized Shiny application and am attempting to do it with the bs4Dash package. This is what the application looks like:
Picture 1
The end application has several sections (I only made the Introduction for this example) and each section contains at least one bs4TabCard. The tabcard in the picture above has one uiOutput and one rhandsontableOutput element, which are rendered in the server function. Note that these are both ***Output elements. In the reproducible code for Picture 1 (which you can find at the end of the question), I do not use any module. However, my goal is to use several modules because the application has the potential to become quite large. For this simple example, I try to use two modules: one module for each section (i.e. each bs4TabItem) and one module for each tabcard. This means that the two modules will invariably be nested: the tabcard module will be inside the section module.
Picture 2
The issue
The issue is that when I implement the modules, the ***Output elements are not displayed:
Picture 3
The surprising thing is that ***Input elements are displayed. I made a third module containing a numericInput only and placed it in the second tab of the tabcard. The picture below shows that the numericInput is displayed with no problem:
Picture 4
I did my homework
In this issue, a similar problem is reported, but there has not been any solution offered and my digging around proved unsuccessful. It seems that there is a problem when an output element is placed deep inside several nested containers in bs4Dash.
The reproducible code
Reproducible code for picture 1
library(shiny)
library(bs4Dash)
library(rhandsontable)
shiny::shinyApp(
ui = bs4DashPage(
old_school = FALSE,
sidebar_min = TRUE,
sidebar_collapsed = FALSE,
controlbar_collapsed = FALSE,
controlbar_overlay = TRUE,
title = "Basic Dashboard",
navbar = bs4DashNavbar(),
sidebar = bs4DashSidebar(
sidebarMenu(
bs4Dash::menuItem(
text = "Introduction",
tabName = "tab-introduction",
icon = ""
)
)
),
controlbar = bs4DashControlbar(),
footer = bs4DashFooter(),
body = bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab-introduction",
bs4TabCard(
id = "tabcard", title = "Tab Card", side = "right",
bs4TabPanel(
tabName = "Tab 1",
uiOutput("ui"),
rHandsontableOutput("hot")
),
bs4TabPanel(
tabName = "Tab 2",
p("Hey")
)
)
)
)
)
),
server = function(input, output) {
output$hot <- renderRHandsontable({ rhandsontable(mtcars[1:10, 1:3]) })
output$ui <- renderUI({
numericInput("num_ui", label = "Num In", value = 15)
})
}
)
Reproducible code for Picture 3 and Picture 4
library(shiny)
library(bs4Dash)
library(rhandsontable)
# Tabcard module ----------------------------------------------------------
mod_tabcard_ui <- function(id){
ns <- NS(id)
bs4TabCard(
id = ns("tabcard"), title = "Tab Card", side = "right",
bs4TabPanel(
tabName = "Tab 1",
uiOutput(ns("ui")),
rHandsontableOutput(ns("hot"))
),
bs4TabPanel(
tabName = "Tab 2",
mod_numinput_ui(ns("num"))
)
)
}
mod_tabcard_server <- function(input, output, session){
output$hot <- renderRHandsontable({ rhandsontable(mtcars[1:10, 1:3]) })
output$ui <- renderUI({
numericInput(session$ns("num_ui"), label = "Num In", value = 15)
})
callModule(mod_numinput_server, "num")
}
# Numeric input module ----------------------------------------------------
mod_numinput_ui <- function(id){
ns <- NS(id)
numericInput(ns("num"), "Num In", 0, 0, 10)
}
mod_numinput_server <- function(input, output, server){
return(reactive({input$num}))
}
# Section module ----------------------------------------------------------
mod_section_ui <- function(id){
ns <- NS(id)
mod_tabcard_ui(id = "tabcard")
}
mod_section_server <- function(input, output, session){
callModule(mod_tabcard_server, id = "tabcard")
}
# The app -----------------------------------------------------------------
shiny::shinyApp(
ui = bs4DashPage(
old_school = FALSE,
sidebar_min = TRUE,
sidebar_collapsed = FALSE,
controlbar_collapsed = FALSE,
controlbar_overlay = TRUE,
title = "Basic Dashboard",
navbar = bs4DashNavbar(),
sidebar = bs4DashSidebar(
sidebarMenu(
bs4Dash::menuItem(
text = "Introduction",
tabName = "tab-introduction",
icon = ""
)
)
),
controlbar = bs4DashControlbar(),
footer = bs4DashFooter(),
body = bs4DashBody(
bs4TabItems(
bs4TabItem(
tabName = "tab-introduction",
mod_section_ui(id = "mod")
)
)
)
),
server = function(input, output) {
callModule(mod_section_server, id = "mod")
}
)
you are missing a namespace in the mod_section_ui module. It should be:
mod_section_ui <- function(id){
ns <- NS(id)
mod_tabcard_ui(id = ns("tabcard"))
}

Async: Display progress when actionButton is hit and disable other operations for the same user but allow concurrent users

Below is a sample code which takes two inputs: 1) input file and 2) input number of rows. Upon clicking the "Analyze" button the output from the server command return to the "Table" in "Results" tabset. This is a simple example where the command will be executed quickly and switches to the "Results" tabsetpanel.
The below withProgress code only shows the progress bar for the set time and disappears and then the actual code is executed. I would like to show a "Status Message" or "Progress Bar" when the "Analyze" is hit and show as long as the command is run. As long as the progress bar is running the current user (other users can use the app) cannot perform any action from the side bar. Because in the real app, sidebar has more menuItems which does similar tasks like this and each task has a Analyze button. If the user is allowed to browse to sidebar pages and hit Analyze then the app will have overload of performing multiple tasks. Ideally the progress bar functionality should we used with multiple actionButtons.
I read the blogs about async but unable to put right code in the right place. any help is appreciated with a bounty!!
library(shiny)
library(shinydashboard)
sidebar <- dashboardSidebar(width = 200,
sidebarMenu(id = "tabs",
menuItem(
"File", tabName = "tab1", icon = icon("fas fa-file")
)))
body <- tabItem(tabName = "tab1",
h2("Input File"),
fluidRow(
tabPanel(
"Upload file",
value = "upload_file",
fileInput(
inputId = "uploadFile",
label = "Upload Input file",
multiple = FALSE,
accept = c(".txt")
),
checkboxInput('header', label = 'Header', TRUE)
),
box(
title = "Filter X rows",
width = 7,
status = "info",
tabsetPanel(
id = "input_tab",
tabPanel(
"Parameters",
numericInput(
"nrows",
label = "Entire number of rows",
value = 5,
max = 10
),
actionButton("run", "Analyze")
),
tabPanel(
"Results",
value = "results",
navbarPage(NULL,
tabPanel(
"Table", DT::dataTableOutput("res_table"),
icon = icon("table")
)),
downloadButton("downList", "Download")
)
)
)
))
ui <-
shinyUI(dashboardPage(
dashboardHeader(title = "TestApp", titleWidth = 150),
sidebar,dashboardBody(tabItems(body))
))
server <- function(input, output, session) {
file_rows <- reactiveVal()
observeEvent(input$run, {
withProgress(session, min = 1, max = 15, {
setProgress(message = 'Analysis in progress',
detail = 'This may take a while...')
for (i in 1:15) {
setProgress(value = i)
Sys.sleep(0.5)
}
})
system(paste(
"cat",
input$uploadFile$datapath,
"|",
paste0("head -", input$nrows) ,
">",
"out.txt"
),
intern = TRUE)
head_rows <- read.delim("out.txt")
file_rows(head_rows)
})
observeEvent(file_rows(), {
updateTabsetPanel(session, "input_tab", "results")
output$res_table <-
DT::renderDataTable(DT::datatable(
file_rows(),
options = list(
searching = TRUE,
pageLength = 10,
rownames(NULL),
scrollX = T
)
))
})
output$downList <- downloadHandler(
filename = function() {
paste0("output", ".txt")
}, content = function(file) {
write.table(file_rows(), file, row.names = FALSE)
}
)
}
shinyApp(ui = ui, server = server)
Here is a solution based on the (absolutely under-star-ed) library(ipc).
I came across this library due to a question of #Dean Attali, where Joe Cheng mentioned it.
The quick-start guide of the ipc-package gives an example of what you are asking for: AsyncProgress.
Furthermore it provides an example on how to kill a future using AsyncInterruptor.
However, I haven't been able to test it yet.
I worked around the cancel-problem by using #Dean Attali's great package shinyjs to simply start a new session and ignore the old Future (You might be able to improve this, by using AsyncInterruptor).
But nevertheless, I gave your code a Future, dropped your system() cmd because I'm currently running R on Windows and found a way to disable (tribute to #Dean Attali) the analyze button session-wise by giving it session-dependant names:
library(shiny)
library(shinydashboard)
library(ipc)
library(promises)
library(future)
library(shinyjs)
library(datasets)
library(V8)
plan(multiprocess)
header <- dashboardHeader(title = "TestApp", titleWidth = 150)
sidebar <- dashboardSidebar(width = 200,
sidebarMenu(id = "tabs",
menuItem(
"File", tabName = "tab1", icon = icon("fas fa-file")
)))
body <- dashboardBody(useShinyjs(),
fluidRow(column(
12, tabItem(
tabName = "tab1",
h2("Input File"),
textOutput("shiny_session"),
tabPanel(
"Upload file",
value = "upload_file",
fileInput(
inputId = "uploadFile",
label = "Upload Input file",
multiple = FALSE,
accept = c(".txt")
),
checkboxInput('header', label = 'Header', TRUE)
),
box(
title = "Filter X rows",
width = 7,
status = "info",
tabsetPanel(
id = "input_tab",
tabPanel(
"Parameters",
numericInput(
"nrows",
label = "Entire number of rows",
value = 5,
max = 10
),
column(1, uiOutput("sessionRun")),
column(1, uiOutput("sessionCancel"))
),
tabPanel(
"Results",
value = "results",
navbarPage(NULL,
tabPanel(
"Table", DT::dataTableOutput("res_table"),
icon = icon("table")
)),
downloadButton("downList", "Download")
)
)
)
)
)))
ui <- shinyUI(dashboardPage(
header = header,
sidebar = sidebar,
body = body,
title = "TestApp"
))
server <- function(input, output, session) {
output$shiny_session <-
renderText(paste("Shiny session:", session$token))
file_rows <- reactiveVal()
run_btn_id <- paste0("run_", session$token)
cancel_btn_id <- paste0("cancel_", session$token)
output$sessionRun <- renderUI({
actionButton(run_btn_id, "Analyze")
})
output$sessionCancel <- renderUI({
actionButton(cancel_btn_id, "Cancel")
})
paste("Shiny session:", session$token)
observeEvent(input[[run_btn_id]], {
file_rows(NULL)
shinyjs::disable(id = run_btn_id)
progress <- AsyncProgress$new(message = 'Analysis in progress',
detail = 'This may take a while...')
row_cnt <- isolate(input$nrows)
get_header <- isolate(input$header)
future({
fileCon <- file("out.txt", "w+", blocking = TRUE)
linesCnt <- nrow(iris)
for (i in seq(linesCnt)) {
Sys.sleep(0.1)
progress$inc(1 / linesCnt)
writeLines(as.character(iris$Species)[i],
con = fileCon,
sep = "\n")
}
close(fileCon)
head_rows <- read.delim("out.txt", nrows = row_cnt, header=get_header)
progress$close() # Close the progress bar
return(head_rows)
}) %...>% file_rows
return(NULL) # Return something other than the future so we don't block the UI
})
observeEvent(input[[cancel_btn_id]],{
session$reload()
})
observeEvent(file_rows(), {
shinyjs::enable(id = run_btn_id)
updateTabsetPanel(session, "input_tab", "results")
output$res_table <-
DT::renderDataTable(DT::datatable(
req(file_rows()),
options = list(
searching = TRUE,
pageLength = 10,
rownames(NULL),
scrollX = T
)
))
})
output$downList <- downloadHandler(
filename = function() {
paste0("output", ".txt")
},
content = function(file) {
write.table(file_rows(), file, row.names = FALSE)
}
)
}
shinyApp(ui = ui, server = server)
App running:
This question has been answered on a different forum
For future reference, if anyone comes across this question, here's the full answer (I did not come up with this answer, it's by Joe Cheng)
This seems to be the main piece of code you're asking about:
observeEvent(input$run, {
withProgress(session, min = 1, max = 15, {
setProgress(message = 'Analysis in progress',
detail = 'This may take a while...')
for (i in 1:15) {
setProgress(value = i)
Sys.sleep(0.5)
}
})
system(paste(
"cat",
input$uploadFile$datapath,
"|",
paste0("head -", input$nrows) ,
">",
"out.txt"
),
intern = TRUE)
head_rows <- read.delim("out.txt")
file_rows(head_rows)
})
With futures/promises, you need to clearly decide what operations happen inside of the Shiny process, and what operations happen in the future process. In this case, here are the steps that we want to happen, in order:
Show progress message (Shiny process)
Read reactives: input$uploadFile$datapath, input$nrows (Shiny)
Write all but the last nrows to out.txt (future process)
Read out.txt (Could be either, let's say future)
Dismiss progress (Shiny)
Assign result to file_rows (Shiny)
Here's what that looks like:
observeEvent(input$run, {
prog <- Progress$new(session)
prog$set(message = "Analysis in progress",
detail = "This may take a while...",
value = NULL)
path <- input$uploadFile$datapath
nrows <- input$nrows
future({
readLines(path) %>% head(-nrows) %>% writeLines("out.txt")
read.delim("out.txt")
}) %...>%
file_rows() %>%
finally(~prog$close())
})
As long as the future/promise pipeline is the last expression in the observeEvent (which it is in this case, as file_rows() and finally(...) are part of the pipeline) then Shiny will hold off on processing any messages on behalf of the user.
There are two things this solution doesn't address.
Progress messages take a step back; not only are we forced to use the Progress$new() syntax instead of the cleaner withProgress(), but we lost the ability to report on the progress percentage. You can try the new ipc package for a solution to that problem.
This doesn't stop the user from clicking around in the UI; it won't do anything while the async operation is executing, but when the operation is done those interactions will have accumulated in a queue and will be handled in the order that they arrived. If you'd like to actually disable the UI entirely so that they're not able to do anything at all, there's not currently a built-in way to do that in Shiny. Although come to think of it, you might try replacing the use of Progress with showModal(modalDialog(title = "Analysis in progress", "This may take a while...", footer=NULL)); I think that will at least stop mouse clicks.