R Shiny中的环境 [英] Environments in R Shiny
问题描述
在 http://shiny.rstudio.com/articles/scoping.html 解释光泽范围的规则得到了很好的解释.彼此嵌套有3个环境或级别:函数内,会话内和所有会话内可用的对象.使用<-将在您所处的环境中更改对象,而<<-将在全局(即针对所有会话)中更改对象.
At http://shiny.rstudio.com/articles/scoping.html the rules for scoping in shiny are well explained. There are 3 environments or levels nested inside each other: objects available within a function, within a session and within all sessions. Using <- will change the object within the environment you are in and <<- will change it globally i.e. for all sessions.
如果我在会话中定义变量但想从函数中更改该变量怎么办?
What if I define a variable within the session but want to change it from within a function?
<-只会在函数内对其进行更改,因此其他功能无法读取,并且<<-将在所有会话中对其进行更改.之间没有什么?像只是上一层"?
<- will just change it within the function so not readable by other functions and <<- will change it for all sessions. Is there nothing inbetween? Like "just one level up"?
推荐答案
感谢您对Stephane的引用.如果在shinyServer()之前定义了对象,则在shinyServer()内的任何地方使用<<-将会更改应用程序所有实例的值.如果对象是在ShinyServer()中定义的,则<< ;-(在函数内部或外部)只会更改该应用实例的值.
Thanks for that reference Stephane. If an object is defined before the shinyServer() then using <<- anywhere within shinyServer() will change the value for all instances of the app. If the object is defined within shinyServer() then <<- (inside or outside a function) will only change the value for that instance of the app.
我将一个带有计数器和实例ID的小应用程序组合在一起进行测试.运行该应用程序的两个实例并在它们之间进行切换以增加计数,这证明了<<-
I put together a little app with a counter and instance ids to test this. Running two instances of the app and switching between them increasing the count demonstrates the effect of <<-
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
这篇关于R Shiny中的环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!