【问题标题】:Dynamic Function in R Studio - Deployment on R ShinyR Studio 中的动态函数 - 在 R Shiny 上部署
【发布时间】:2020-01-04 23:21:35
【问题描述】:

我在 R 中有一个完整的函数,它接受一些输入参数并返回一个矩阵。我想在 Shiny 应用程序上构建相同的内容。函数的输入参数应该是滑块输入,输出应该是动态的。

我尝试使用反应函数来改变输入。

     names<- c("A", "B", "C", "D", "E")
     ages<- c(25,24,23,22,21)
     salary<- c(60000,32000,37000,15000,15000)
     data<- data.frame(names,ages, salary)
     header<- dashboardHeader(title="Dynamic")

     sidebar<- dashboardSidebar(sidebarMenu(
     id="id",
     sliderInput("age","AGE",min = 0, max = 50, value = "20")
     ))

     body<- dashboardBody(box(
     dataTableOutput("view")
     ))

     ui<- dashboardPage(header, sidebar, body)

     try_function<- function(age){
     to_show<- data %>% filter(ages>age)
     return(to_show) 
     }

    server<- function(input, output, session) {   
      output$view <- renderDataTable({
        reactive({try_function(input$age)
        })    
      })     
    }

    shinyApp(ui, server)

任何人都可以帮助解决这个问题。 假设如果我有多个输入,那么这段代码应该如何变化。

我希望输出会根据闪亮应用上的参数而有所不同。这不会给我任何错误,但也不会在 Shiny 上显示任何输出。

【问题讨论】:

    标签: r function dynamic shiny


    【解决方案1】:

    一般来说,我们不应该在render 表达式中使用reactive 调用。当我们对返回值感兴趣或函数没有“副作用”时,通常使用反应式表达式。删除reactive() 调用,解决了这里的问题。

    library(shiny)
    library(tidyverse)
    library(shinydashboard)
    
    names<- c("A", "B", "C", "D", "E")
    ages<- c(25,24,23,22,21)
    salary<- c(60000,32000,37000,15000,15000)
    data<- data.frame(names,ages, salary)
    header<- dashboardHeader(title="Dynamic")
    
    sidebar<- dashboardSidebar(sidebarMenu(
      id="id",
      sliderInput("age","AGE",min = 0, max = 50, value = 20)
    ))
    
    body<- dashboardBody(box(
      dataTableOutput("view")
    ))
    
    ui<- dashboardPage(header, sidebar, body)
    
    try_function<- function(age){
      to_show<- data %>% filter(ages>age)
      return(to_show) 
    }
    
    server<- function(input, output, session) {   
    
      output$view <- renderDataTable({
        try_function(input$age)
      })     
    
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 感谢@Sada93 的编辑另外,如果我想包含多个参数,那么任何建议
    • 多个参数改成什么?
    • 我不需要在函数内部的任何地方都写年龄作为 input$age 吗??????
    猜你喜欢
    • 2016-12-09
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 2015-05-13
    • 1970-01-01
    • 2015-07-21
    • 2023-01-25
    相关资源
    最近更新 更多