Error in dynamically choosing a dataset in shiny dashboard - r

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

Related

Adding a sliderInput to a ggplot line chart in ShinyDashboard

I've been struggling to add a functional slider input to my ggplot line chart for "number of observations", but I keep getting errors .. The code below works but the plot does not change ( I tried lots of stuff like adding a reactive function or adding input$obs inside ggplot but it still didn't work) .. I really appreciate your help ! Thanks
library(shiny)
library(shinydashboard)
library(readxl)
library(ggplot2)
library(dashboardthemes)
library(shinyWidgets)
library(dplyr)
df=read_excel("MASI.xlsx")
# Define UI for application that draws a histogram
ui <- dashboardPage(
dashboardHeader(title = "Finance Dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(
title = "Line chart", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot1", height = 250)
),
box(
title = "MASI", status = "primary", solidHeader = TRUE,
"The MASI index (Moroccan All Shares Index) is a stock index that tracks the performance of all
companies listed in the Casablanca Stock Exchange located at Casablanca."
),
box(
title = "Inputs", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs",
"Number of observations:",
min = 1,
max = length(df$MASI),
value = 50)
),
),
),
setBackgroundColor(
color = "white",
gradient = c("linear", "radial"),
direction = c("bottom", "top", "right", "left"),
shinydashboard = TRUE
)
)
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(df,aes(x=Session, y=MASI)) + geom_line( color="darkblue", size=0.7) + theme_bw()
}, bg="transparent")
}
shinyApp(ui, server)
EDIT
Thank you for the kind answer #chemdork123.
I want to add a Date range in addition to the sliderInput. Here's what I did:
library(shiny)
library(shinydashboard)
library(readxl)
library(ggplot2)
library(dashboardthemes)
library(shinyWidgets)
library(dplyr)
df=read_excel("MASI.xlsx")
# Define UI for application that draws a histogram
box_height = "20em"
plot_height = "16em"
ui <- dashboardPage(
dashboardHeader(title = "Finance Dashboard"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(
title = "Line chart", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot1", height = 250)
),
box(
title = "MASI", status = "primary", solidHeader = TRUE,
"The MASI index (Moroccan All Shares Index) is a stock index that tracks the performance of all
companies listed in the Casablanca Stock Exchange located at Casablanca."
),
box(
title = "Inputs", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs",
"Number of observations:",
min = 1,
max = length(df$MASI),
value = 50),
dateRangeInput("date", strong("Date range"),
start = "2015-01-02", end = "2020-07-17",
min = "2015-01-02", max = "2020-07-17")
),
box(
title = "Line chart", status = "success", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot2", height = 250)
),
box(
title = "Return", status = "success", solidHeader = TRUE,
"The relative difference of the MASI index"
),
box(
title = "Inputs", status = "success", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs",
"Number of observations:",
min = 1,
max = length(df$MASI),
value = 50)
),
),
),
setBackgroundColor(
color = "white",
gradient = c("linear", "radial"),
direction = c("bottom", "top", "right", "left"),
shinydashboard = TRUE
)
)
server <- function(input, output) {
reactive_data <- reactive({
set.seed(8675309) # for some consistent sampling
df <- df[sample(x=1:nrow(df), size = input$obs),]
return(df)
req(input$date)
validate(need(!is.na(input$date[1]) & !is.na(input$date[2]), "Error: Please provide both a start and an end date."))
validate(need(input$date[1] < input$date[2], "Error: Start date should be earlier than end date."))
df %>%
filter(
date > as.POSIXct(input$date[1]) & date < as.POSIXct(input$date[2]
))
})
output$plot1 <- renderPlot({
ggplot(reactive_data(),aes(x=Session, y=MASI)) + geom_line(color="darkblue", size=0.7) + theme_bw()
}, bg="transparent")
output$plot2 <- renderPlot({
ggplot(df,aes(x=Session, y=Return)) + geom_line( color="darkblue", size=0.7) + theme_bw()
}, bg="transparent")
}
shinyApp(ui, server)
Here is a link for the Dataset
Capture
OP. Without your data, it's difficult to give you a clear answer to your particular question, but I can show you how the input$obs slider input control can be used (or any other one for that matter) to filter and provide data for your ggplot() function to display.
Here's a working app that gives you two controls to adjust what data is displayed from the mtcars built-in dataset. The sliderInput() control determines how many rows are sampled from the total mtcars dataset. The selectInput() control allows you to select one or all of the values for mtcars$carb to display in the chart based on the sampled dataset.
You will see the general approach on how to use both inputs reactively is to create a reactive function (called sample_cars()) that is called inside of the renderPlot() function. The reactive function sample_cars() returns a data frame that is used in the ggplot() call.
library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(tidyr)
ui <- dashboardPage(
dashboardHeader(title = "Example App"),
dashboardSidebar(),
dashboardBody(
# Boxes need to be put in a row (or column)
fluidRow(
box(
title = "Line chart", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot1", height = 250)),
box(
title = "Inputs", status = "primary", solidHeader = TRUE, collapsible = TRUE,
sliderInput("obs", "Number of observations:",
min = 1, step = 1, max = nrow(mtcars), value = nrow(mtcars)),
selectInput("carbs", "Select carb to show",
choices = c('All', unique(mtcars$carb))
)
),
)
)
)
server <- function(input, output) {
sample_cars <- reactive({
set.seed(8675309) # for some consistent sampling
df <- mtcars[sample(x=1:nrow(mtcars), size = input$obs),]
if(input$carbs != "All")
df <- df %>% dplyr::filter(carb == input$carbs)
return(df)
})
output$plot1 <- renderPlot({
ggplot(sample_cars(), aes(mpg, disp)) + geom_point() +
labs(title=paste('You selected',input$obs, 'cars\n and to show',input$carbs, 'values of carb!'))
}, bg="transparent")
}
shinyApp(ui, server)

closing sidebar in shiny dashboard

I am trying to make a multipage shiny dashboard. I would like the sidebar to collapse when you pick a page, with the ability to reopen it to pick a new page. For example, when you pick page 2 the sidebar collapses and you can reopen it later if you want to go back to page 1. Right now it is stuck open, i.e. when you click page 2 the sidebar does not collapse. I used useShinyjs(), which is what I thought makes it collapsible with no luck. Any help is much appreciated :)
library(shiny)
library(dplyr)
library(shiny)
library(shinydashboard)
library(shinyjs)
library(shinyWidgets)
library(shinyBS)
library(plotly)
Stores <- data.frame(Store = c("Store 1", "Store 2", "Store 3", "Store 4", "Store 5"),
Sales = c(8247930, 423094, 204829, 903982, 7489472, 429085, 208955, 7492852, 5285034, 2958275,1598753, 28487593, 4892049, 583042, 509275, 5904728, 5098325, 5920947, 4920946, 2049583),
Avg_cust = c(325,542,582,482,904, 594, 304, 493, 690, 403, 694, 104, 493, 596, 403, 506, 304, 305, 632, 478),
Year = c(rep(2012,5), rep(2013,5), rep(2014,5), rep(2015,5)))
ui <- dashboardPage(
header = dashboardHeader(
title = "Store Performance",
titleWidth = "100%"),
sidebar = dashboardSidebar(
useShinyjs(),
width = 200,
collapsed = FALSE,
sidebarMenu(id = "tabs",
menuItem("Page 1", tabName = "pg1"),
menuItem("Page 2", tabName = "pg2"))),
skin = "black",
body = dashboardBody(
useShinyjs(),
tabItems(
tabItem("pg1",
fluidRow(
column(width = 3,
box(
title = "Options",
status = 'warning',
solidHeader = TRUE,
width = 12,
collapsible = FALSE,
collapsed = FALSE,
pickerInput(
inputId = "YR",
label = "Year:",
choices = c(2012,2013,2014,2015),
selected = 2015,
multiple = FALSE))),
column(width = 9,
boxPlus(plotlyOutput("All"),
status = 'warning',
width = 12,
solidHeader = TRUE,
collapsible = FALSE,
closable = FALSE,
collapsed = FALSE)))),
tabItem("pg2",
fluidRow(
column(width = 9,
boxPlus(title = "Add graph here",
width = 12,
status = "warning",
solidHeader = TRUE,
collapsible = FALSE,
closable = FALSE,
collapsed = FALSE)),
column(width = 3,
box(
title = "Options",
status = 'warning',
solidHeader = TRUE,
width = 12,
collapsible = FALSE,
collapsed = FALSE,
pickerInput(
inputId = "st",
label = "Store:",
choices = unique(Stores$Store),
selected = "Store 1",
multiple = FALSE
))))))))
server <- function(input, output) {
observeEvent({
input$YR
},
output$All <- renderPlotly({
plot_ly(Stores[Stores$Year == input$YR,], x = ~Avg_cust, y = ~Sales,
hoverinfo = "text", text = ~Store)%>%
layout(title = "Store Performance",
xaxis = list(title = "Customers"),
yaxis = list(title = "Sales"))
})
)
}
shinyApp(ui = ui, server = server)
Only using useShinyjs() doesn't do the trick. It only sets up shinyjs, but you need to tell it what to do. The idea here is to add the class "sidebar-collapse" to the body, as this hides the sidebar. The sidebar should always been hidden if a tab was switched, so have to add an observer that listens if a tab was switched. Then you can use shinyjs to add the class with addClass. The input of the tabswitch is the id of the sidebarMenu:
library(shiny)
library(dplyr)
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)
library(shinyWidgets)
library(shinyBS)
library(plotly)
Stores <- data.frame(Store = c("Store 1", "Store 2", "Store 3", "Store 4", "Store 5"),
Sales = c(8247930, 423094, 204829, 903982, 7489472, 429085, 208955, 7492852, 5285034, 2958275,1598753, 28487593, 4892049, 583042, 509275, 5904728, 5098325, 5920947, 4920946, 2049583),
Avg_cust = c(325,542,582,482,904, 594, 304, 493, 690, 403, 694, 104, 493, 596, 403, 506, 304, 305, 632, 478),
Year = c(rep(2012,5), rep(2013,5), rep(2014,5), rep(2015,5)))
ui <- dashboardPage(
header = dashboardHeader(
title = "Store Performance"),
sidebar = dashboardSidebar(
width = 200,
collapsed = FALSE,
sidebarMenu(id = "tabs",
menuItem("Page 1", tabName = "pg1"),
menuItem("Page 2", tabName = "pg2"))),
skin = "black",
body = dashboardBody(
useShinyjs(),
tabItems(
tabItem("pg1",
fluidRow(
column(width = 3,
box(
title = "Options",
status = 'warning',
solidHeader = TRUE,
width = 12,
collapsible = FALSE,
collapsed = FALSE,
pickerInput(
inputId = "YR",
label = "Year:",
choices = c(2012,2013,2014,2015),
selected = 2015,
multiple = FALSE))),
column(width = 9,
box(plotlyOutput("All"),
status = 'warning',
width = 12,
solidHeader = TRUE,
collapsible = FALSE,
closable = FALSE,
collapsed = FALSE)))),
tabItem("pg2",
fluidRow(
column(width = 9,
box(title = "Add graph here",
width = 12,
status = "warning",
solidHeader = TRUE,
collapsible = FALSE,
closable = FALSE,
collapsed = FALSE)),
column(width = 3,
box(
title = "Options",
status = 'warning',
solidHeader = TRUE,
width = 12,
collapsible = FALSE,
collapsed = FALSE,
pickerInput(
inputId = "st",
label = "Store:",
choices = unique(Stores$Store),
selected = "Store 1",
multiple = FALSE
))))))))
server <- function(input, output) {
output$All <- renderPlotly({
plot_ly(Stores[Stores$Year == input$YR,], x = ~Avg_cust, y = ~Sales,
hoverinfo = "text", text = ~Store)%>%
layout(title = "Store Performance",
xaxis = list(title = "Customers"),
yaxis = list(title = "Sales"))
})
observeEvent(input$tabs, {
addClass(selector = "body", class = "sidebar-collapse")
})
}
shinyApp(ui = ui, server = server)
BTW: you also need the package shinydashboardPlus. Also, I removed your observer because I don't know what you want to achieve. Lastly, I reduced the width of the header, because otherwise the button to show the sidebar is hidden.
For more information how it works, have a look here and here.

Having different tabs and different UI for each tab in Shiny

I am trying to create two tabs and for each tab in shiny I want to have different UI for each tab.
I am able to create two tabs and the problems i face is the UI is not specific for each tab and when I add the second tab, the UI in the first tab doesn't work. Any idea how to resolve these issues?
The code looks like this:
#Library
library(shiny)
library(shinydashboard)
#Run the Source
pdf(NULL)
#Shiny Header/Sidebar/Body
header=dashboardHeader(title = "FTA Risk Center")
sidebar=dashboardSidebar(sidebarMenu(id = "sidebarmenu",
menuItem("Risk Dashboard", tabName = "Flow", icon = icon("dashboard")),
menuItem("HKJAP", tabName = "HKJAP", icon = icon("th")),
menuItem("HKKOR", tabName = "HKKOR", icon = icon("th"))
))
body=dashboardBody(
tabItems(tabItem(tabName = "HKJAP",uiOutput('output1'),
fluidRow(column(width = 3,box(title = "Summary of EQ Delta", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",tableOutput("EOD"))),column(width = 3,box(title = "Summary of FX Delta", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",tableOutput("FX"))),column(width = 3,box(title = "Unmapped Tickers", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",tableOutput("UnmappedTickers")))),
fluidRow(column(width = 8,box(title = "Exposures by Indices", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",plotOutput("Chart1"))))),
tabItem(tabName = "HKKOR",uiOutput('output2'),
fluidRow(column(width = 3,box(title = "Summary of EQ Delta", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",tableOutput("EOD"))),column(width = 3,box(title = "Summary of FX Delta", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",tableOutput("FX"))),column(width = 3,box(title = "Unmapped Tickers", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",tableOutput("UnmappedTickers")))),
fluidRow(column(width = 8,box(title = "Exposures by Indices", width = NULL, collapsible = TRUE, solidheader = TRUE,status = "primary",plotOutput("Chart2")))))
)
)
ui <- dashboardPage(header,sidebar,body)
#Shiny Server
server <- function(input, output,session) {
observeEvent(input$sidebarmenu,{
if(input$sidebarmenu == "HKJAP")
{
obsJAP <- observeEvent(reactiveTimer(30000)(),{ # Trigger every 30 seconds
source("HKJAP_Live_monitor_v1.R")
obsJAP$destroy()
})
output$output1 <- renderUI({
invalidateLater(30000, session)
h1(paste("Risk Exposures as of ",Sys.time()))
})
output$EOD=renderTable({
invalidateLater(30000, session)
EQ_delta_summary_Live})
output$FX=renderTable({
invalidateLater(30000, session)
FX_delta_summary_Live})
output$UnmappedTickers=renderTable({
invalidateLater(30000, session)
unmapped_tickers})
output$Chart1=renderPlot({
invalidateLater(30000, session)
plot(NIKKEI$trade_time,cumsum(NIKKEI$EQ_Delta),type='l',xlim=time_scale,ylim=c(-30,30), main=paste("Main Indices"),lwd=2)
grid(10,10,lty=5)
lines(TOPIX$trade_time,cumsum(TOPIX$EQ_Delta),type='l',col="red",lwd=3)
lines(NIKKEI_400$trade_time,cumsum(NIKKEI_400$EQ_Delta),type='l',col="orange",lwd=3)
lines(MXJ$trade_time,cumsum(MXJ$EQ_Delta),type='l',col="green",lwd=3)
lines(TSE_MOTHERS$trade_time,cumsum(TSE_MOTHERS$EQ_Delta),type='l',col="blue",lwd=3)
lines(REITS$trade_time,cumsum(REITS$EQ_Delta),type='l',col="pink",lwd=3)
legend("topright",c("TOPIX","NIKKEI","NIKKEI 400","MXJ","TSE_M","REITS"),lty = c(1,1),col = c("red","black","orange","green","blue","pink"),,bty = 'n',cex = 0.8)
})
}else if(input$sidebarmenu == "HKKOR"){
obsKOR <- observeEvent(reactiveTimer(30000)(),{ # Trigger every 30 seconds
source("HKKOR_Live_monitor_v1.R")
obsKOR$destroy()
})
output$output2 <- renderUI({
invalidateLater(30000, session)
h1(paste("Risk Exposures as ",Sys.time()))
})
output$EOD=renderTable({
invalidateLater(30000, session)
EQ_delta_summary_Live})
output$FX=renderTable({
invalidateLater(30000, session)
FX_delta_summary_Live})
output$UnmappedTickers=renderTable({
invalidateLater(30000, session)
unmapped_tickers})
output$Chart2=renderPlot({
invalidateLater(30000, session)
plot(KOSPI_DIV$trade_time,cumsum(KOSPI_DIV$EQ_Delta),type='l',xlim=time_scale,ylim=c(-30,30), main=paste("Main Indices"),lwd=2)
grid(10,10,lty=5)
lines(KOSPI$trade_time,cumsum(KOSPI$EQ_Delta),type='l',col="red",lwd=3)
lines(KOSDAQ$trade_time,cumsum(KOSDAQ$EQ_Delta),type='l',col="orange",lwd=3)
lines(KRX$trade_time,cumsum(KRX$EQ_Delta),type='l',col="green",lwd=3)
lines(MSCI_KOR$trade_time,cumsum(MSCI_KOR$EQ_Delta),type='l',col="blue",lwd=3)
lines(SPX_HKKOR$trade_time,cumsum(SPX_HKKOR$EQ_Delta),type='l',col="pink",lwd=3)
legend("topright",c("KOSPI_DIV","KOSPI","KOSDAQ","KRX","MSCI_KOR","SPX"),lty = c(1,1),col = c("black","red","orange","green","blue","pink"),,bty = 'n',cex = 0.8)
})
}
}
)
}
shinyApp(ui, server)

How to print the summary of a variable in R shiny?

I would like that based on a selectInput() which the client can select, the summary of the selected variable will be print in a box. My code for the ui.R is:
box(
title = "Informed Investor",
status = "primary",
solidHeader = TRUE,
width = 6,
selectInput("informedDset", label="Select Category", choices = list("Informed Full" = "InformedFull", "Informed Fact" = "InformedFact", "Informed Fact Positive" = "InformedFact.Pos", "Informed Fact Negative" = "InformedFact.Neg", "Informed Emotions" = "InformedEmotions", "Informed Emotions Fact" = "InformedEmotionsFact"), selected = "Informed Full")
),
box(
title = "Data Table",
status = "warning",
solidHeader = TRUE,
width = 6,
height = 142,
verbatimTextOutput("summaryDset")
)
And my code for server.R:
output$summaryDset <- renderPrint({
summary(input$informedDset)
})
As indicated in the comments, summary returns Length Class Mode 1 character character because the input$informedDset is a character string.
If you want to extract the summary of one selected variable in a dataset you can find an reproducible example below with the iris dataset :
library(shiny)
library(shinydashboard)
ui=fluidPage(
box(title = "Informed Investor",
status = "primary",
solidHeader = TRUE,
width = 6,
selectInput("informedDset", label="Select Category",
choices = list("Sepal.Length"="Sepal.Length",
"Sepal.Width"="Sepal.Width",
"Petal.Length"="Petal.Length",
"Petal.Width"="Petal.Width",
"Species"="Species"), selected = "Sepal.Length")),
box(
title = "Data Table",
status = "warning",
solidHeader = TRUE,
width = 6,
height = 142,
verbatimTextOutput("summaryDset")))
server = function (input,output){
output$summaryDset <- renderPrint({
summary(iris[[input$informedDset]])
})}
shinyApp(ui, server)
Is that what you want to do ?

Print str() of table in shiny dashboard

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...

Resources