R Shiny中的环境

斯坦博克

http://shiny.rstudio.com/articles/scoping.html上,对光泽范围进行定义的规则得到了很好的解释。彼此嵌套有3个环境或级别:函数内,会话内和所有会话内可用的对象。使用<-将更改您所处环境中的对象,而<<-将全局更改该对象,即用于所有会话。

如果我在会话中定义变量但想在函数中更改该怎么办?

<-只会在函数中更改它,因此其他函数无法读取它,而<<-将在所有会话中更改它。之间没有什么?像“只是上一层楼”?

斯坦博克

感谢您的参考Stephane。如果在ShinyServer()之前定义了一个对象,则在<< ShirtServer()中的任何地方使用<<-将更改应用程序所有实例的值。如果对象是在ShinyServer()中定义的,则<<-(在函数内部或外部)将仅更改该应用程序实例的值。

我将一个带有计数器和实例ID的小应用放在一起进行测试。运行该应用程序的两个实例并在它们之间进行切换以增加计数,这证明了<<-的效果

用户界面

    library(shiny)

shinyUI(pageWithSidebar(

  headerPanel("Testing Environments"),

  sidebarPanel(


    actionButton("increment_counter", "Increase Count")


  ),

  mainPanel(

    tabsetPanel(
      tabPanel("Print", verbatimTextOutput("text1"))


      ))

))

服务器

instance_id<-1000

shinyServer(function(input, output, session) {

  instance_id<<-instance_id+1
  this_instance<-instance_id

  counter<-0


  edit_counter<-reactive({

    if(input$increment_counter>counter){
    counter<<-counter+1
    }

    list(counter=counter)

  })



  output$text1 <- renderPrint({ 
    cat(paste("Session ID: ",Sys.getpid()," \n"))
    cat(paste("Global Instance ID: ",instance_id," \n"))
    cat(paste("This Instance ID: ",this_instance," \n"))
    cat(paste("Button Value: ",input$increment_counter," \n"))
    cat(paste("Counter Value: ",edit_counter()$counter," \n"))


  })



}) # end server function

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章