r - 在 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)
解决方案
@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)
推荐阅读
- python - 如何使用 % 格式打印浮点变量?
- python - AWS Lambda 如何执行函数?
- typescript - Typescript:防止数字到数组的隐式类型转换
- python - 如何在该循环外使用来自循环的计数
- mysql - 选择日期字段值不在当前月份和年份的记录
- ios - 使用 IOS SDK 将报告的属性发送到 Azure IOT Central
- vue.js - 如何检查文件类型是否是 vue.js 中指定的文件类型(图像)?
- sql - PL/pgSQL 对两个 json 或两行逐字段求和
- sql - 如何从上一个 9 月获得 9 月 1 日?
- android - 设备解锁时防止应用更改为纵向