Shiny ui中相互依赖的小部件

时间:2017-01-12 22:40:57

标签: r shiny

我正在运行当前版本的RStudio,R和所有R软件包。

在下面的示例代码中,我的目标是设置xcol和ycol的最大值,以便将它们限制为正在绘制的数据框中的列数。下面的代码导致错误"对象'输入'没找到。"我怀疑问题可能是我在ui依赖中制作小部件,但这是我的猜测。这是问题,是否有一种策略可供我解决。

我查看了包含相同错误的帖子,但无法找到任何可以回答我问题的帖子(或者无法识别回答的时间。)我发现的最接近的帖子是:{{3} }; R Shiny error: object input not found; R Shiny renderImage() does not recognize object 'input'; Error in eval: object 'input' not found in R Shiny app

以下是一些可重现的随机数据代码。

library(tidyverse)
library(cluster)
library(vegan)
library(shiny)

dta <- rnorm(100, mean = 0, sd = 1)
mat <- matrix(dta, nrow = 10)
dm <- daisy(mat, metric = "euclidean") %>% as.matrix()

server <- function(input, output) {
    output$plot <- renderPlot({
        nmds <- metaMDS(dm, distance = "euclidean", k = input$dim, trymax = 2000, autotransform = FALSE, noshare = FALSE, wascores = FALSE)
        df <- nmds$points %>% as.data.frame()
        plot(df[,input$xcol], df[,input$ycol])
    }, height = 500, width = 500)
}

ui <- fluidPage(
        sidebarLayout(
        sidebarPanel(
            numericInput("dim", "Number of dimensions", value = 2, min = 2, max = 12),
            numericInput("xcol", "X column", value = 1, min = 1, max = input$dim),
            numericInput("ycol", "Y column", value = 2, min = 1, max = input$dim)
        ),
            mainPanel(
                plotOutput("plot")
        )
      )
    )

1 个答案:

答案 0 :(得分:0)

您可以使用updateNumericInput从服务器修改UI:

# Modify ui to use initial max
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput("dim", "Number of dimensions", value = 2, min = 2, max = 12),
      numericInput("xcol", "X column", value = 1, min = 1, max = 2),
      numericInput("ycol", "Y column", value = 2, min = 1, max = 2)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)


# Modify server to update max when dim changes 
# (notice the session parameter needed for updateNumericInput)
server <- function(input, output, session) {
  output$plot <- renderPlot({
    if(input$xcol>input$dim)
      updateNumericInput(session, "xcol", value=input$dim, max=input$dim)
    else
      updateNumericInput(session, "xcol", max=input$dim)
    if(input$ycol>input$dim)
      updateNumericInput(session, "ycol", value=input$dim, max=input$dim)
    else
      updateNumericInput(session, "ycol", max=input$dim)
    nmds <- metaMDS(dm, distance = "euclidean", k = input$dim, trymax = 2000, autotransform = FALSE, noshare = FALSE, wascores = FALSE)
    df <- nmds$points %>% as.data.frame()
    plot(df[,min(input$dim,input$xcol)], df[,min(input$dim,input$ycol)])
  }, height = 500, width = 500)
}