Print str() of table in shiny dashboard - r

I am a newbie to shiny dashboard. I want to know how to print str() of the table which i have imported in shiny dashboard. my code is not working. When i print str(), i get the below output,
str()
Please check the code which i have written,
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Analytics Workbench 2.0", titleWidth = 250,
dropdownMenuOutput("msgs")),
dashboardSidebar(
sidebarMenu(
fileInput("Table1", "Train Data"),
fileInput("Table2", "Test Data"),
menuItem("Variable Analysis", icon = icon("edit"),
menuSubItem("Uni-Variate Analysis"),
menuSubItem("Multi-Variate Analysis"))
)
),
dashboardBody(
fluidRow(
column(12, box(title = "Train Data", width = 6, solidHeader = TRUE, status = "warning",
collapsible = TRUE, DT::DTOutput("Train")),
box(title = "Test Data", width = 6, solidHeader = TRUE, status = "warning",
collapsible = TRUE, DT::DTOutput("Test")))),
fluidRow(
column(12, box(title = "Structure", width = 6, solidHeader = TRUE, status = "warning",
collapsible = TRUE, verbatimTextOutput("str1")),
box(title = "Structure", width = 6, solidHeader = TRUE, status = "warning",
collapsible = TRUE, verbatimTextOutput("str2"))))
)
)
server <- function(input, output) {
output$msgs <- renderMenu({
msg <- apply(read.csv("messages.csv"), 1, function(row){
messageItem(from = row[["from"]], message = row[["message"]]) })
dropdownMenu(type = "messages", .list = msg)
})
output$Train <- DT::renderDT({
if (is.null(input$Table1)) return(NULL)
data1 <- read.table(input$Table1$datapath, fill = TRUE, header=T, sep=",")
DT::datatable(data1, options = list(scrollX = TRUE))
})
output$Test <- DT::renderDT({
if (is.null(input$Table2)) return(NULL)
data2 <- read.table(input$Table2$datapath, fill = TRUE, header=T, sep=",")
DT::datatable(data2, options = list(scrollX = TRUE))
})
output$str1 <- renderText({
paste(capture.output(str(input$Table1)), collapse = "\n")
})
output$str2 <- renderText({
paste(capture.output(str(input$Table1)), collapse = "\n")
})
}
I am not able to find out the input to be given for str()
Thanks
Balaji

Switch out your textOutput for verbatimTextOutput. Also, you require a reactive to treat the fileInput... specifically take note that you should trap the case when the input value is NULL.
app.R
library(shiny)
write.csv(mtcars, "mtcars.csv") # file created to test file input
ui <- fluidPage(
mainPanel(
verbatimTextOutput("strfile"),
fileInput("file1", "File")
)
)
server <- function(input, output) {
df <- reactive({
if (is.null(input$file1)) {
return(NULL)
} else {
read.csv(input$file1$datapath, row.names = 1) # note the row.names are dependent on your input requirements
}
})
output$strfile <- renderPrint({str(df())})
}
shinyApp(ui = ui, server = server)
To get this output...

Related

invalid argument to unary operator error in Shiny dashboard

I want to delete a selected variable from the dataset in R shinydashboard. Please find attached my code. But when I try to select a variable and delete,
if(input$imputation == "Delete Variable"){
rv$Train <- rv$Train[,-(input$miss_var)]
return(rv$Train)
}
I get the following error,
Warning: Error in -: invalid argument to unary operator
UI
Please find the ui part of the code,
library(shiny)
library(shinydashboard)
library(missForest)
ui <- dashboardPage(skin = "black",
dashboardHeader(title = "Analytics Workbench 2.0", titleWidth = 250, dropdownMenuOutput("msgs")),
dashboardSidebar(
sidebarMenu(
fileInput("Table1", "Historical Data"),
radioButtons("sep", "Separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t", Pipe="|"), selected = ","),
menuItem("Variable Transformation", tabName = "transformation",icon = icon("exchange")))),
dashboardBody(
tabItems(
tabItem(tabName = "transformation",
fluidRow(
box(selectInput("miss_var", "Variable", c("1"="1","2"="2")), width = 2, status = "primary"),
box(title = "Missing Value Imputation", width = 4, status = "primary", solidHeader = TRUE, collapsible = TRUE,
radioButtons("imputation", label = "",
choices = list(Delete_Variable = "Delete Variable", Impute = "Impute"), selected = ""),
actionButton("miss_imp", "Select"))))
)
)
)
SERVER
Please find the server part of the code,
server <- function(input, output, session) {
## initialize
rv <- reactiveValues()
## update when dataset changes
observe({
rv$Train <- read.table(req(input$Table1)$datapath, fill = TRUE, header=T,
sep=input$sep, na.strings = c(""," ",NA),
stringsAsFactors = TRUE)
})
observe({
is.miss <- sapply(rv$Train, function(y) sum(length(which(is.na(y)))))
dname3 <- names(rv$Train[, is.miss > 0])
col_options3 <- list()
col_options3[dname3] <- dname3
updateSelectInput(session, "miss_var",
label = "Missing Variables",
choices = col_options3,
selected = "")
})
observeEvent(input$miss_imp,{
if(input$imputation == "Delete Variable"){
rv$Train <- rv$Train[,-(input$miss_var)]
return(rv$Train)
} else if(input$imputation == "Impute"){
missfor <- missForest(rv$Train)
rv$Train <- data.frame(missfor$ximp)
return(rv$Train)
}
})
}
shinyApp(ui, server)
Thanks,
Balaji

Error in dynamically choosing a dataset in shiny dashboard

I am a newbie to shiny dashboard. I want to dynamically select a dataset among different datasets uploaded and use it to display the dataset.
I have written the below code but i am getting an error,
Warning: Error in DT::datatable: 'data' must be 2-dimensional (e.g. data frame or matrix)
ui
ui <- dashboardPage(skin = "yellow",
dashboardHeader(title = "Analytics Workbench 2.0", titleWidth = 250,
dropdownMenuOutput("msgs")),
dashboardSidebar(
sidebarMenu(
fileInput("Table1", "Train Data"),
fileInput("Table2", "Test Data"),
menuItem("Variable Analysis", icon = icon("edit"),
menuSubItem("Uni-Variate Analysis"),
menuSubItem("Multi-Variate Analysis"))
)
),
dashboardBody(
fluidPage(
fluidRow(
column(12, box(title = "Train Data", width = 6, solidHeader = TRUE, status = "primary",
collapsible = TRUE, DT::DTOutput("dtable1")),
box(title = "Test Data", width = 6, solidHeader = TRUE, status = "primary",
collapsible = TRUE, DT::DTOutput("dtable2")))),
fluidRow(
column(12, box(title = "Structure", width = 6, solidHeader = TRUE, status = "primary",
collapsible = TRUE, verbatimTextOutput("str1")),
box(title = "Structure", width = 6, solidHeader = TRUE, status = "primary",
collapsible = TRUE, verbatimTextOutput("str2"))))
)
)
)
server
server <- function(input, output) {
Train <- reactive({
if (is.null(input$Table1)) return(NULL)
read.table(input$Table1$datapath, fill = TRUE, header=T, sep=",", na.strings = c(""," ",NA))
})
Test <- reactive({
if (is.null(input$Table2)) return(NULL)
read.table(input$Table2$datapath, fill = TRUE, header=T, sep=",", na.strings = c(""," ",NA))
})
dataset_1 <- reactive({
switch(input$Datasets,
"Train" = Train,
"Test" = Test)
})
output$dtable2 <- DT::renderDT({
DT::datatable(dataset_1(), options = list(scrollX = TRUE))
}) }
Please help me solve this issue.
Thanks Balaji

R Shiny : Save and load progress

I am working on a Shiny App that uses rhandsontable and I would like to provide the user an option to save and load the progress. A minimal example of my code is as follows:
library(shinydashboard)
library(shiny)
library(data.table)
library(rhandsontable)
library(markdown)
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("file")),
menuItem("Control", tabName = "control", icon = icon("list-alt"))
)
)
body <- dashboardBody(
tabItems(
tabItem(tabName = "data",
fluidRow(
box(title = h3("Input data manually or by importing a .csv file:"),
#fileInput("file1", "Choose CSV File:", width = '30%',
# multiple = TRUE,
# accept = c("text/csv",
# "text/comma-separated-values,text/plain",
# ".csv")),
width = 12, height = 800, rHandsontableOutput("hot"))
)
),
tabItem(tabName = "control",
fluidRow(
actionButton("save", "Save"), actionButton("load", "Load"),
box(title = h2("1. General Information"), width = '100%',
radioButtons("Type",
h4("Type:"),
choices = list("1" = "1", "2" = "2")),
radioButtons("DataExtraction",
h4("Extract information:"),
choices = list("Yes" = "Yes", "No" = "No"), selected = "No")
)
)
)
)
)
ui <- dashboardPage(
dashboardHeader(title = "Shiny"),
sidebar,
body
)
server <- function(input, output, session) {
observeEvent(input$load,{
values <<- readRDS("C:/Documents/ws1.RData")
if (exists("values")) {
lapply(names(values),
function(x) session$sendInputMessage(x, list(value = values[[x]]))
)
}
})
observeEvent(input$save,{
values <<- lapply(reactiveValuesToList(input), unclass)
saveRDS( values , file = "C:/Documents/ws1.RData")
})
filedata <- reactive({
inFile <- input$file1
if (is.null(inFile)){
data.table(Number1 = numeric(20),
Number2 = numeric(20),
Date1 = seq(from = Sys.Date(), by = "days", length.out = 20),
Date2 = seq(from = Sys.Date(), by = "days", length.out = 20))
} else{
fread(input$file1$datapath)
}
})
output$hot = renderRHandsontable({
rhandsontable(filedata()) %>%
hot_cols(columnSorting = TRUE) %>%
hot_table(highlightCol = TRUE, highlightRow = TRUE)
})
}
shinyApp(ui, server)
I am encountering two issues:
When I include the fileInput("file1", ...), the inputs do not update
anymore once I click the load action button;
The Rhandsontable is not updated. However, when I look into values$hot$data, it does seem as if the data is properly stored in values.
Does anyone have an idea of what I am doing wrong?
Thanks!

Adding a vertical and horizontal scroll bar to the DT table in R shiny

Please check the data table "Case Analyses Details" on the right. I want to fit the data table within the box, such that it aligns from right and bottom border in the box, such that we add a horizontal and vertical scroll bar to the DT which can be used to span the rows that overshoot the box.
## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "My Chart"),
dashboardSidebar(
width = 0
),
dashboardBody(
box(title = "Data Path", status = "primary",height = "595" ,solidHeader = T,
plotOutput("trace_plot")),
box( title = "Case Analyses Details", status = "primary", height =
"595",width = "6",solidHeader = T,
div(DT::dataTableOutput("trace_table",width = 220)))
))
server <- function(input, output)
{
#Plot for Trace Explorer
output$trace_plot <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width)
})
output$trace_table <- renderDataTable({
mtcars
})
}
shinyApp(ui, server)
Something like this do?
rm(list = ls())
## app.R ##
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "My Chart"),
dashboardSidebar(
width = 0
),
dashboardBody(
box(title = "Data Path", status = "primary",height = "595" ,solidHeader = T,
plotOutput("trace_plot")),
box( title = "Case Analyses Details", status = "primary", height =
"595",width = "6",solidHeader = T,
column(width = 12,
DT::dataTableOutput("trace_table"),style = "height:500px; overflow-y: scroll;overflow-x: scroll;"
)
)))
server <- function(input, output) {
#Plot for Trace Explorer
output$trace_plot <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width)
})
output$trace_table <- renderDataTable({
datatable(cbind(mtcars,mtcars), options = list(paging = FALSE))
})
}
shinyApp(ui, server)
This is an old question, but we can also use the dedicated options scrollX and scrollY to add scrollbars to the datatable:
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "My Chart"),
dashboardSidebar(
width = 0
),
dashboardBody(
box(title = "Data Path", height = 450,
plotOutput("trace_plot")),
box(title = "Case Analyses Details", height = 450,
DTOutput("trace_table")
))
)
server <- function(input, output) {
output$trace_plot <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width)
})
output$trace_table <- renderDataTable({
datatable(
cbind(mtcars, mtcars),
options = list(
scrollX = TRUE,
scrollY = "250px"
)
)
})
}
shinyApp(ui, server)

shiny app with own function

I want to implement a function in a Shiny app. My own function get_calculate() has the arguments data and tolerance as input and retruns a list with a data.frame and a plot.
I want to show the output depending on tolerance. In my server function I use reactive() to run get_calculate() but it doesn't work.
If I write in renderPlot() and renderDataTable() get_calculate() works.
For large datasets, however, it's inefficient because Shiny will have to run get_calculate() twice.
library(shiny)
library(shinydashboard)
library(foreign)
#load my own function
source("01-get_calculate.R")
ui <- dashboardPage(
dashboardHeader(title = "Analysis"),
dashboardSidebar(
sidebarMenu(
menuItem("Load data", tabName = "data", icon = icon("database")),
menuItem("Mainboard", tabName = "Mainboard", icon = icon("dashboard"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "data",
fileInput("datafile", "Choose file",
accept = c("text/csv/rds/dbf", 'text/comma-separated-values,text/plain')),
dataTableOutput("mytable")
),
tabItem(tabName = "Mainboard",
fluidRow(
box(
title = "Input", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput(inputId = "tol",
label = "Tolerance",
value = 4, min = 1, max = 15, step = 1)
)),
fluidRow(
box(
title = "Adherence Curve", status = "warning", solidHeader = TRUE, collapsible = TRUE,
plotOutput("plot_kpm")
),
box(
title = "Overview Table", status = "primary", solidHeader = TRUE, collapsible = TRUE,
tableOutput("table_kpm")
)
)
)
)
)
)
server <- function(input, output) {
filedata <- reactive({
infile <- input$datafile
if (is.null(infile)) {
return(NULL)
}
read.dbf(infile$datapath)
})
output$mytable <- renderDataTable({
filedata()
})
**test <- reactive({
get_calculate(filedata(), tolerance = input$tol)
})
output$plot_kpm <- renderPlot({
test$kpm_chart
})
output$table_kpm <- renderDataTable({
test$data_kpm[, c("Time", "numbers", "Percent")]
})**
}
shinyApp(ui = ui, server = server)
The error you mentioned is most likely from renderDataTable where you are trying to pick couple of columns from test$data_kpm. Check the dataframe for exact column names.
This version of my shiny app runs. But it' ineffcient because shiny have to runs get_calculate twice.
server <- function(input, output) {
#This function is repsonsible for loading in the selected file
filedata <- reactive({
infile <- input$datafile
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
read.dbf(infile$datapath)
})
output$mytable <- renderDataTable({
filedata()
})
output$plot_kpm <- renderPlot({
get_calculate(filedata(), tolerance = input$tol)$kpm_chart
})
output$table_kpm <- renderTable({
get_calculate(filedata(), tolerance = input$tol)$data_kpm[, c("Time", "Percent", "Patients")]
})
output$download_mainboard_adherence_table <- downloadHandler(
filename = paste("adherence_table", '.csv', sep=''),
content = function(file) {
write.csv(get_calculate(filedata(), tolerance = input$tol)$data_kpm[, c("Time", "Percent", "Patients")], file)
}
)
}
Why don't you use a reactive expression to run your get_calculate just once ? And then use the result in your output$plot_kpm and output$table_kpm ?
This will optimize your code.

Resources