首页 > 解决方案 > 在 Shiny 中运行 R 函数需要纠正什么

问题描述

我想让以下简单的 R 函数在Shiny. 它在R.

LifeExpectancy <- function(Age){
    X <- which(lifeExpCH$Alter == Age)
    LifeE <- lifeExpCH$`2018`[X:100]
    Y <- seq(Age, 99, 1)
    df1 <- data.frame(LifeE, Y)
    ggplot(df1, aes(Y, LifeE)) +
    geom_line() +
    labs(x = “Age”, y = “Years Expected to Live”, title = “Life Expectancy Switzerland 2018”)
    }

我写的东西Shiny不起作用。

很高兴得到一些帮助,谢谢。

ui <- fluidPage(
     sidebarLayout(
         sidebarPanel(
             numericInput(inputId = "Age", label = "Enter your age", value = 30, min = 0, max = 99)
         ),
        mainPanel(
             plotOutput(outputID = "LifeExp_plot")
         )
     )
 )
     LifeExpectancy <- function(Age){
     X <- which(lifeExpCH$Alter == Age)
     LifeE <- lifeExpCH$`2018`[X:100]
     Y <- seq(Age, 99, 1)
     df1 <- data.frame(LifeE, Y)
     return(df1)
 }
 server <- function(input, output){
     LifeExpectancy <- reactive ({
         LifeExpectancy(input$Age)
     })
     output$LifeExp_plot <- renderPlot({
         ggplot(LifeExpectancy, aes(Y, LifeE) ) +
geom_line()     
     })  
 }
 shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


@Martin - 我希望这可能会有所帮助。我无法运行,因为我没有lifeExpCH可用的。

注意我重命名了你的计算函数,LifeExpectancyFromAge以区别于你的reactive函数。当你调用你的reactive函数时,一定要使用括号。

library(shiny)
library(ggplot2)

LifeExpectancyFromAge <- function(Age){
  X <- which(lifeExpCH$Alter == Age)
  LifeE <- lifeExpCH$`2018`[X:100]
  Y <- seq(Age, 99, 1)
  df1 <- data.frame(LifeE, Y)
  return(df1)
}

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput(inputId = "Age", label = "Enter your age", value = 30, min = 0, max = 99)
    ),
    mainPanel(
      plotOutput(outputId = "LifeExp_plot")
    )
  )
)

server <- function(input, output){
  LifeExpectancy <- reactive ({
    LifeExpectancyFromAge(input$Age)
  })
  output$LifeExp_plot <- renderPlot({
    ggplot(LifeExpectancy(), aes(Y, LifeE)) +
      geom_line() +
      labs(x = "Age", y = "Years Expected to Live", title = "Life Expectancy Switzerland 2018")
  })  
}

shinyApp(ui = ui, server = server)

推荐阅读