【问题标题】:shinydashboard ui.R and server.R not reading Global.Rshinydashboard ui.R 和 server.R 未读取 Global.R
【发布时间】:2017-02-01 16:42:17
【问题描述】:

在 RStudio 中开发时,我成功地使用 global.R 将数据传递给 ui.r 和 server.R。但是,当我将代码迁移到服务器时,ui.R 和 server.R 都无法读取 global.R。我正在使用 Shiny Server(不是专业版)。这可能是什么原因造成的?

我的代码看起来像这样(它不是反应式的)

#global.R
x = 10

#ui.R
print(x)
> 10 #in RStudio viewer
> Error: object 'x' not found #on Shiny Server

根据下面 sigmabeta 的回答,我对 server.Rglobal.R 进行了更改,但是我正在寻找服务器将 x 重置为另一个值,以便 ui.R 可以读取它。这就是我现在的代码

#global.R
x = 10
get_x_value <- function (n) {
x = n+1        
return x
}

#server.R
source("./global.R")

shinyServer(function(input, output) {
values <- reactiveValues()
observe ({
    values$x <- get_x_value(5)
})
})

#ui.R
print(x)
> 6 #in RStudio viewer
> 10 #on Shiny Server

这是ui.R 中的实际代码,我试图根据server.R 中已经计算的值来设置框的状态

library(shinydashboard)
dashboardPage(
  Header = dashboardHeader(title = 'Test'), 
  Sidebar = dashboardSidebar
  (
  sidebarMenu
  (
  menuItem("ABC", tabName = "ABC")
  )
  ),
  Body = dashboardBody
  (tabItems
  (
  tabItem(
    tabName = "ABC",
    fluidRow
    (
    box
    (
    status = if (x==6) "info" else "danger" ,
    solidHeader = TRUE
    )
    )
  )
  )
  )
)

【问题讨论】:

    标签: shiny shiny-server shinydashboard


    【解决方案1】:

    您似乎没有提到您的闪亮应用程序必须从 global.R 获取值(和/或)函数

    您可以在 server.R 文件中执行此操作。 server.R 示例代码:

    library(shiny)
    
    source("./global.R")
    
    shinyServer(function(input, output) {
    values <- reactiveValues()
    observe ({
        values$x <- get_x_value()
    })
    output$text1 <- renderText({
       values$x
    })
    
    })
    

    然后在 global.R 中,您将拥有函数 get_x_value,如下所示:

    get_x_value <- function () {
        x = 10
        return x
    }
    

    x 也可以在外面定义,如果有的话,你可能想在函数中做一些额外的处理,或者编写更复杂的函数。

    更新: 添加ui.R的代码

    shinyUI(fluidPage(
    mainPanel(
        htmlOutput(
            textOutput("text1")
        )
    ))
    

    【讨论】:

    • 谢谢。这有帮助。但是,使用此解决方案,我无法从 server.R 更新 global.R 中的任何变量
    • 你需要使用响应式值。我将编辑我的答案以解释您如何反应地做到这一点
    • 我仍然无法从服务器更新 x。我编辑了我的问题以显示我在寻找什么。
    • This article 实际上恰恰相反:不需要需要采购。也许是否需要 source("global.R") 从一个版本的 Shiny 更改为另一个版本?
    • 您不需要来源global.R,它只需要与server.Rui.R 在同一目录中即可。注意shinyApp 调用不能将global.Rapp.R 编织在一起;但是,这是通过 shinyAppDir 自动完成的。参见。 ?shinyAppstackoverflow.com/questions/54914541/global-r-dont-start/…
    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2019-07-16
    • 2020-01-20
    • 2017-03-06
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    相关资源
    最近更新 更多