【问题标题】:use pre assigned variable inside R shiny function as a parameter使用 R 闪亮函数中的预分配变量作为参数
【发布时间】:2018-08-01 18:08:42
【问题描述】:

我正在使用 R shiny 创建一个调查,并在我的 Shiny 应用程序的开头具有以下功能:

install.packages("devtools")
spotifydata<-spotifycharts::chart_top200_weekly()
s<-spotifydata$artist
h<-head(s,20)

我想知道是否有任何地方可以显示变量“h”的输出??

我的想法是通过以下方式使用“selectInput”以下拉菜单的方式显示每个结果。

 selectInput("artists","pick 3 artists out of the top 10",
              c("h[1]","h[2]","h[3]","h[4]","h[5]","h[6]",
                "h[7]","h[8]","h[9]","h[10]"),multiple = TRUE)

我知道这会产生错误但我想知道是否有办法模拟这个

【问题讨论】:

    标签: r shiny shinyjs


    【解决方案1】:

    selectInput 中,变量应该不带引号,如下所示:

     selectInput("artists","pick 3 artists out of the top 10",
                    c(h[1],h[2],h[3],h[4],h[5],h[6],
                      h[7],h[8],h[9],h[10]),multiple = TRUE)
    

    以下是一个展示其工作原理的应用:

    library(shiny)
    
    spotifydata<-spotifycharts::chart_top200_weekly()
    s<-spotifydata$artist
    h<-head(s,20)
    
    ui <- fluidPage(
        selectInput("artists","pick 3 artists out of the top 10",
                    c(h[1],h[2],h[3],h[4],h[5],h[6],
                      h[7],h[8],h[9],h[10]),multiple = TRUE)
    )
    
    server <- function(input, output)
    {}
    
    shinyApp(ui, server) 
    

    输出如下:

    请注意,通过这种方法,变量h在不同的用户会话之间共享

    如果您不希望变量 h 在不同的用户会话之间共享,您可以使用以下方法,我们在服务器函数中获取 h 值并使用函数 updateSelectInput 更新选择输入的选择

    ui <- fluidPage(
      selectInput("artists","pick 3 artists out of the top 10",
                  choices = c(), multiple = TRUE)
    )
    
    server <- function(input, output, session)
    {
      observe({
    
        spotifydata<-spotifycharts::chart_top200_weekly()
        s<-spotifydata$artist
        h<-head(s,20)
    
        updateSelectInput(session, inputId = "artists", choices = c(h[1],h[2],h[3],h[4],h[5],h[6],
                                                                    h[7],h[8],h[9],h[10]))
    
      })
    
    }
    
    shinyApp(ui, server) 
    

    【讨论】:

    • 谢谢。此外,您可以使用 choices = h[1:10] 代替将 10 个选项中的每一个都输入为 h[1], h[2]....
    猜你喜欢
    • 2021-05-27
    • 2013-08-08
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多