Nicolas123
Nicolas123

Reputation: 131

Source function does not work - Shiny Dashboard

I am trying to create my DashboardBody() in different script but it gives me an error. I have saved all my workings that are related to Dashboard body in Dashboard_body.R script and I call this script in my main app

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Dashboard Basic"),
  
  dashboardSidebar(),
  
  source("Dashboard_body.R", local = TRUE)
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider)]
    hist(data)
  })
}

shinyApp(ui, server)
dashboardBody(
  # Boxes need to be put in a row (or column)
  fluidRow(
    box(plotOutput("plot1", height = 250)),
    
    box(
      title = "Controls",
      sliderInput("slider", "Number of observations:", 1, 100, 50)
    )
  )
)

Error in tagAssert(body, type = "div", class = "content-wrapper") : 
  Expected an object with class 'shiny.tag'.

Upvotes: 1

Views: 431

Answers (1)

MrFlick
MrFlick

Reputation: 206167

The source() function will return a list with the last value and whether or not is was visible. To access the value, you can do

ui <- dashboardPage(
  dashboardHeader(title = "Dashboard Basic"),
  dashboardSidebar(),
  source("Dashboard_body.R", local = TRUE)$value
)

But really, if you are sourcing a file it's better to keep proper functions in there. That makes it much easier to reuse.

So have something like

get_body <- function() {
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(plotOutput("plot1", height = 250)),
      box(
        title = "Controls",
        sliderInput("slider", "Number of observations:", 1, 100, 50)
      )
    )
  )
}

Then you would source before creating the UI and call your function

source("Dashboard_body.R")
ui <- dashboardPage(
  dashboardHeader(title = "Dashboard Basic"),
  dashboardSidebar(),
  get_body()
)

Upvotes: 3

Related Questions