使用 R 闪亮函数中的预分配变量作为参数

use pre assigned variable inside R shiny function as a parameter

我正在使用 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)

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

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 值并更新 [=32= 的选择] 使用函数 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)