r-如何包含反应输出文本Shiny



我使用的是多文件设置,因此我同时拥有ui.r和server.r文件。我使用的是下面的数据集(小样本(,该数据集着眼于2016年美国/加拿大不同州/省的不明飞行物目击事件。

Date        Time           AM.PM   Country       City   State   Shape
1   12/21/2016     7:15:00          PM     USA      Waynesboro    VA    Sphere
2   12/21/2016     12:00:00         AM     USA      Louisville    KY    Unknown
3   12/20/2016     10:30:00         PM     USA      Santa Rosa    CA    Sphere
4   12/20/2016     7:00:00          PM     USA      Fresno        CA    Circle
5   12/19/2016     9:53:00          PM     USA      Reymert       AZ    Circle
6   1/11/2016      8:15:00          PM     CANADA   Mississauga   ON    Circle

到目前为止,在我的应用程序中,我已经创建了一个显示条形图的主面板,该条形图具有在";形状";x轴上的列和y轴上的观测次数。我在侧面有一个小部件,用户可以选择是想查看美国还是加拿大的数据,绘图会相应地改变。我想做的是在主面板中的情节下输出文本;观察最多的形状:;然后打印具有最高y值的形状的名称。对我来说,困难的部分是,打印的形状的名称需要根据图形上当前显示的数据进行更改。感谢您的帮助!

UI文件:

library(shiny)
library(ggplot2)
library(dplyr)
shinyUI(fluidPage(
# Application title
titlePanel("Exploring UFO Sightings"),
sidebarLayout(
sidebarPanel(
selectInput("Country",
"Country to Display:",
choices = list("USA" = 'USA',
"Canada" = 'CANADA'),
),
checkboxGroupInput("type",
"Select Desired Shapes Observed:",
choices = unique(ufo_data$Shape),
selected = unique(ufo_data$Shape)),
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("ufoPlot"),
# textOutput("Shape with the most observations:")
)
)
))

服务器文件:

library(shiny)
library(ggplot2)
library(dplyr)

shinyServer(function(input, output) {
output$ufoPlot <- renderPlot({

ufo_data_filter <- filter(ufo_data, Country == input$Country & Shape %in% input$type)
ggplot(data = ufo_data_filter) +
geom_bar(mapping = aes(x = Shape, fill = Shape))+
labs(
title = "Number of Different Shaped UFO Observations in Selected Country",
x = "Shape of UFO Sighted",
y = "Number of Observations in 2016"
)
})
})

对于选择的数据子集,可以使用count查找每个Shape的计数,并选择出现次数最多的一个。

library(shiny)
library(ggplot2)
library(dplyr)
ui <- fluidPage(
# Application title
titlePanel("Exploring UFO Sightings"),
sidebarLayout(
sidebarPanel(
selectInput("Country",
"Country to Display:",
choices = list("USA" = 'USA',
"Canada" = 'CANADA'),
),
checkboxGroupInput("type",
"Select Desired Shapes Observed:",
choices = unique(ufo_data$Shape),
selected = unique(ufo_data$Shape)),
),

# Show a plot of the generated distribution
mainPanel(
plotOutput("ufoPlot"),
textOutput("text")
)
)
)
server <- function(input, output) {

output$ufoPlot <- renderPlot({

ufo_data_filter <- filter(ufo_data, Country == input$Country & Shape %in% input$type)
ggplot(data = ufo_data_filter) +
geom_bar(mapping = aes(x = Shape, fill = Shape))+
labs(
title = "Number of Different Shaped UFO Observations in Selected Country",
x = "Shape of UFO Sighted",
y = "Number of Observations in 2016"
) 
})

output$text <- renderText({
text_data <- ufo_data %>%
filter(Country == input$Country & Shape %in% input$type) %>%
count(Shape, sort = TRUE)
paste0('Shape with the most observations: ', text_data$Shape[1])
})
}
shinyApp(ui, server)

最新更新