我已经为在R Shiny上收集的一些橄榄球数据编写了一个基本的Web应用程序。该脚本可以执行,但是我想在已编写的内容上构建以包含更多数据,并且我觉得必须有一种方法可以简化或合并所编写的代码,以使构建代码更加容易。
我正在做一个时间序列,比较玩家参与的7个位置区域中的玩家质量指标(BMI,身高和体重)。
该应用程序的链接在这里:[玩家质量的演变:橄榄球联盟]
Front Row: BMI, CM, KG
Second Row: BMI, CM, KG
Back Row: BMI, CM, KG
Scrumhalf: BMI, CM, KG
Flyhalf: BMI, CM, KG
Centre: BMI, CM, KG
Outside Back: BMI, CM, KG
#### BMI: Front Row ####
gg1 <- ggplot()+
geom_point(data=dfRUG, aes(x=Debut, y=BMI),colour="slategray", size=3, alpha=0.5)+
geom_point(data=dfRUG[which(dfRUG$Role=="Front Row"),], aes(x=Debut, y=BMI),colour="red", size=3, alpha=0.5)+
geom_smooth(data=dfRUG[which(dfRUG$Role=="Front Row"),], aes(x=Debut, y=BMI),se=F, colour="black")+
theme_fivethirtyeight()+theme(axis.title=element_text(size=12))+
labs(title = "Mass Evolution of Rugby Internationals", x="Year of Debut", y="Body Mass Index",
subtitle = "Position: Front Row")
我制作了21个ggplots,将它们组合成一个列表,并使用“ if”和“ else”来决定要根据用户输入调用什么图。
plots <- list(gg1,gg2,gg3,gg4,gg5,gg6,gg7,
gg8,gg9,gg10,gg11,gg12,gg13,gg14,
gg15,gg16,gg17,gg18,gg19,gg20,gg21)
ui.R和server.R行如下所示:
ui <- fluidPage(
wellPanel(h3("Variables"),
radioButtons(inputId = "yvar", label = h4("Mass Metric"),
choices = list("Body Mass Index" = "BMI", "Weight (KG)" = "KG","Height (CM)" = "CM"),
selected = "BMI"),
selectInput(inputId = "zone", choices = dataset$Zone
)
),
mainPanel(
plotOutput("graf")
)
)
server <- function(input, output) {
selectedData <- reactive({
c(input$yvar, input$zone)
})
output$graf <- renderPlot({
if ((input$yvar == "BMI") & (input$zone == "Front Row")){
plots[[1]]
} else if ((input$yvar == "BMI") & (input$zone == "Second Row")){
plots[[2]]
} else if ((input$yvar == "BMI") & (input$zone == "Back Row")){
plots[[3]]
} else if ((input$yvar == "BMI") & (input$zone == "Scrumhalf")){
plots[[4]]
} else if ((input$yvar == "BMI") & (input$zone == "Flyhalf")){
plots[[5]]
} else if ((input$yvar == "BMI") & (input$zone == "Centre")){
plots[[6]]
} else if ((input$yvar == "BMI") & (input$zone == "Outside Back")){
plots[[7]]
}
})
}
这些“ if”和“ else”行中有21条,分别对应于“位置”和“质量”的每种可能组合。
我想将这21行代码合并为更适合处理更多数据组合的内容,而不是调用100个图表。
I use
switch()
in such scenarios. In your case there may be an even easier solution by naming the listnames(plots) <- dataset$Zone
. You can then pick the graph withplots[[input$zone]]
.