我正在探索 Shiny 的交互式 ggplot2 的可能性。灵感来自this我创建了一个 Shiny 的应用程序,它从数据集中排除点,并绘制数据,其中排除的点具有不同的颜色。
应用程序.R
library(shiny)
library(ggplot2)
server<-function(input, output) {
data <- reactive({
set.seed(10)
df=data.frame(x=rnorm(100),y=rnorm(100))
df
})
vals<-reactiveValues(keeprows=rep(TRUE, 100))
output$plot1 <- renderPlot({
df=data()
keep=df[vals$keeprows, ,drop=FALSE]
exclude=df[!vals$keeprows, ,drop=FALSE]
plot=ggplot(data=keep,aes(x,y))+geom_point()+theme_bw()+
geom_point(data=exclude,fill=NA,col="black",alpha=0.75,shape=21)
plot
})
observeEvent(input$plot1_click,{
df=data()
res <- nearPoints(df, input$plot1_click, allRows = TRUE,threshold=5)
vals$keeprows <- xor(vals$keeprows, res$selected_)
})
}
ui <- fluidPage(
titlePanel("Reactive test"),
mainPanel(
plotOutput("plot1",click="plot1_click")
)
)
shinyApp(ui = ui, server = server)
这工作得很好,但现在我希望能够定义 vals:
vals<-reactiveValues(keeprows=rep(TRUE,nrow(CustomDataInput))
在我的示例中,我尝试访问 data() 中创建的数据的行数:
vals<-reactiveValues(keeprows=rep(TRUE,nrow(data()))
这给了我一个错误,因为我试图在非 react 性环境中访问 react 性变量。有没有办法访问 react 函数中创建的数据来定义reactiveValues?
感谢您的宝贵时间!
最佳答案
该错误几乎解决了问题。正确的做法如下。
library(shiny)
library(ggplot2)
server<-function(input, output) {
vals <- reactiveValues()
data <- reactive({
set.seed(10)
df=data.frame(x=rnorm(100),y=rnorm(100))
vals$keeprows = rep(TRUE,nrow(df))
df
})
#vals<-reactiveValues(keeprows=rep(TRUE,100))
output$plot1 <- renderPlot({
df=data()
keep=df[vals$keeprows, ,drop=FALSE]
exclude=df[!vals$keeprows, ,drop=FALSE]
plot=ggplot(data=keep,aes(x,y))+geom_point()+theme_bw()+
geom_point(data=exclude,fill=NA,col="black",alpha=0.75,shape=21)
plot
})
observeEvent(input$plot1_click,{
df=data()
res <- nearPoints(df, input$plot1_click, allRows = TRUE,threshold=5)
vals$keeprows <- xor(vals$keeprows, res$selected_)
})
}
ui <- fluidPage(
titlePanel("Reactive test"),
mainPanel(
plotOutput("plot1",click="plot1_click")
)
)
shinyApp(ui = ui, server = server)
事先声明 vals
变量,并在 reactive()
函数中使用该变量将变量发送到 vals
,如上所示。你应该没问题。
关于r - 访问从 react 函数创建的数据以定义 Shiny 中的 react 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538572/