首页 > 解决方案 > eventReactive 对所有输入值做出反应

问题描述

我似乎不理解反应性。我认为我因为我使用 eventReactive 定义了 myPlot,所以它只会在单击 actionButton 时更新绘图。但是,它会针对所有反应值进行更新。

然后,我尝试使用隔离将对 input$abscissa 和 input$ordinate 的调用包装在 eventReactive 中,但这导致绘图永远不会更新(轴标签除外)。

这是一个代表。按“绘图”按钮创建绘图。如果您更改其中一个主成分,绘图将更新。我该如何阻止它?

library(tidyverse)
library(shiny)

cmat <- 
  data.frame(
    matrix(
      c(2, 3, 5, 7, 11, 13, 17, 
        19, 23, 29, 31, 37, 41, 43, 
        47, 53, 59, 61, 67, 71, 73, 
        79, 83, 89, 97, 101, 103, 107, 
        109, 113, 127, 131, 137, 139, 149, 
        151, 157, 163, 167, 173, 179, 181, 
        191, 193, 197, 199, 211, 223, 227
      ), 
      nrow = 7
    )
  )
names(cmat) <- paste0(rep("V",7),1:7)

numPC <- dim(cmat)[[2]]-2

PC_choices <- paste0(rep("V",numPC),1:(numPC))

ordinals <- c('First', 'Second', 'Third', 'Fourth', 'Fifth',
              'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth')

myPCs <- paste0(ordinals[1:min(numPC,10)],
                rep(" Principal Component", min(numPC,10)))

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      actionButton(
        inputId = "refresh",
        label = "Plot"
      ),
      hr(),
      h5("Choose the Principal Components"),
      radioButtons(
        inputId = "abscissa",
        label = "Abscissa",
        choices = myPCs
      ),
      uiOutput(
        outputId = "yAxis"
      )
    ),
    mainPanel(
      plotOutput(
        outputId = "pcplot"
      )
    )
  )
)

server <- function(input, output){

  output$yAxis <- renderUI({
    radioButtons(
      inputId = "ordinate",
      label = "Ordinate",
      choices = myPCs[-1*which(myPCs==input$abscissa)]
    )
  })

  myPlot <- eventReactive(input$refresh,{
      cmat %>% 
      ggplot(
        aes(
          x = .[,which(myPCs==input$abscissa)],
          y = .[,which(myPCs==input$ordinate)],
          fill = V6
        )
      ) +
      geom_point(shape = 21, color = "black", size = 4) +
      geom_vline(xintercept = median(cmat[,which(myPCs==input$abscissa)]), 
                 linetype = "dashed", 
                 size = 1, 
                 color = "yellow") +
      geom_hline(yintercept = median(cmat[,which(myPCs==input$ordinate)]), 
                 linetype = "dashed", 
                 size = 1, 
                 color = "yellow") +
      scale_fill_gradientn(colors = c("white", "cyan", "blue", "black")) +
      labs(
        title = "PCPLOT",
        x = input$abscissa,
        y = input$ordinate,
        fill = "Response"
      ) +
      theme_bw()
  })

  output$pcplot <- renderPlot({
    myPlot()
  })

}

shinyApp(ui = ui, server = server)

标签: rshinyreactive-programming

解决方案


问题是aes()属性被懒惰地评估。您需要使用一些元编程在代码运行时实际插入输入值,而不是在绘制时。利用

  ggplot(
    aes(
      x = .[,which(myPCs==!!(input$abscissa))],
      y = .[,which(myPCs==!!(input$ordinate))],
      fill = V6
    )
  )

这会将 的值插入input$abscissaaes()而不是表达式input$abscissa中。请注意,您不必为xintercept=oryintercept=值执行此操作,因为它们在aes().


推荐阅读