问题描述
我试图在不同的脚本中创建我的 DashboardBody(),但它给了我一个错误。我已在 Dashboard_body.R 脚本中保存了与仪表板主体相关的所有工作,并在主应用程序中调用了此脚本
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'.
解决方法
source()
函数将返回一个列表,其中包含最后一个值以及是否可见。要访问该值,您可以执行
ui <- dashboardPage(
dashboardHeader(title = "Dashboard Basic"),dashboardSidebar(),source("Dashboard_body.R",local = TRUE)$value
)
但实际上,如果您要采购文件,最好在其中保留适当的功能。这使得重用变得更加容易。
所以有类似的东西
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)
)
)
)
}
然后您将在创建 UI 之前获取源代码并调用您的函数
source("Dashboard_body.R")
ui <- dashboardPage(
dashboardHeader(title = "Dashboard Basic"),get_body()
)