【问题标题】:How to use variables in a switch statement?如何在 switch 语句中使用变量?
【发布时间】:2015-09-29 14:35:59
【问题描述】:

我有大约 50 个文件需要在 dataSource1dataSource2dataSource3 中调用。与其将其全部复制到每个 switch 语句中,不如我如何使用变量,这样我只需在代码顶部输入一次?我在server.R 中调用这个来作为一个闪亮的应用程序。

dataSource1 <- reactive({
        switch(input$dataSelection1,
               "File1" = File1,
               "File2" = File2,
               "File3" = File3,
               "File50" = File50
)
        )

相反,我想要:

dataSource1 <- reactive({
            switch(input$dataSelection1,
                   FileNumber = File
                   )
        )
dataSource2 <- reactive({
            switch(input$dataSelection1,
                   FileNumber = File
                   )
        )
dataSource2 <- reactive({
            switch(input$dataSelection1,
                   FileNumber = File
                   )
        )

【问题讨论】:

    标签: shiny rstudio


    【解决方案1】:

    您可以使用get 函数来返回命名对象的值。假设 input$dataSelection1 具有变量的完整名称,您的反应函数可能是这样的:

     dataSource1 <- reactive({
                get(input$dataSelection1)
            )
    

    它将返回与名称匹配的变量的内容。

    如果input$dataSelection1 只包含一个数字,您可以使用paste0sprintf 函数来构建变量的名称:

    get(paste0('File',input$dataSelection1)) # it will create File1, File2...
    sprintf('File%04d',input$dataSelection1) # add zeros before the number File0001
    

    希望对你有帮助。

    【讨论】:

    • 感谢您的回复,Geovany。我还有一个问题要问你。我已将其附加到原始问题。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多