2014-05-01 57 views
6

http://shiny.rstudio.com/articles/scoping.html有光泽范围的规则很好地解释。有3个环境或层级相互嵌套:功能内,会话内和所有会话内可用的对象。使用< - 将更改您所处环境中的对象,并且将全局更改它,即所有会话。R Shiny中的环境

如果我在会话中定义了一个变量但想从函数内改变它会怎么样?

< - 只会改变它的功能,使其他功能不可读取,并且< - 将改变它的所有会话。中间没有什么?像“只有一级”?

+0

我认为(不确定)这句话的措辞不是很好,“<< - ”意思是“一层一层”。 –

+0

你的意思是说,在一个函数内使用<< - 应该改变函数和闪亮的会话中的变量,但不是一成不变的,即对于所有闪亮的会话?这不符合我的(小)经验。我将有一个更详细的外观/实验,并在这里发布结果。 – steinbock

+1

'<< - '不代表“全球”,而是“非本地”。请阅读Yihui Xie在[本次讨论]中的评论(https://groups.google.com/d/topic/shiny-discuss/sqo6Ve_kveo/discussion) –

回答

7

谢谢你的参考Stephane。如果在shinyServer()之前定义了一个对象,然后使用< - 在shinyServer()中的任何位置将更改该应用的所有实例的值。如果该对象在shinyServer()中定义,那么< - (函数内部或外部)只会更改该应用程序实例的值。

我把一个小应用程序与一个计数器和实例ID来测试这个。运行应用程序的两个实例以及它们之间的切换增加计数演示< <效果 -

ui.r

library(shiny) 

shinyUI(pageWithSidebar(

    headerPanel("Testing Environments"), 

    sidebarPanel(


    actionButton("increment_counter", "Increase Count") 


), 

    mainPanel(

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


    )) 

)) 

server.r

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 
+0

感谢您的“小应用”。在不同的地方看到<<的不同效果是非常有用的。 –