library(shiny)
library(DT)
##
## Attaching package: 'DT'
## The following objects are masked from 'package:shiny':
##
## dataTableOutput, renderDataTable
library(readr)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(lubridate)
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
# 确保已经安装了DT包
if (!requireNamespace("DT", quietly = TRUE)) {
install.packages("DT")
}
# 假设你的数据文件路径正确
billboard_data <- read_csv("billboard.csv", show_col_types = FALSE)
# 定义UI
ui1 <- fluidPage(
titlePanel("Billboard Top Songs Explorer"),
sidebarLayout(
sidebarPanel(
sliderInput("yearRangesong",
"选择年份范围:",
min = 1959,
max = 2019,
value = c(1959, 2019),
step = 1)
),
mainPanel(
DT::DTOutput("topSongsTable") # 使用DT::前缀明确指定DTOutput
)
)
)
# 定义服务器逻辑
server1 <- function(input, output, session) {
output$topSongsTable <- DT::renderDT({ # 使用DT::前缀明确指定renderDT
filtered_data <- billboard_data %>%
mutate(week_id = mdy(week_id)) %>% # 使用mdy()函数解析日期
filter(year(week_id) >= input$yearRangesong[1], year(week_id) <= input$yearRangesong[2]) %>%
group_by(song, performer) %>%
summarise(
TotalWeeks = n(), # 计算每首歌曲在Billboard Top 100中出现的总周数
PeakPosition = min(week_position), # 计算每首歌曲的最高排名位置
.groups = 'drop'
) %>%
arrange(desc(TotalWeeks)) %>% # 按在榜总周数降序排列
slice_max(order_by = TotalWeeks, n = 20) # 选择排名前20的歌曲
DT::datatable(filtered_data, options = list(pageLength = 20)) # 使用DT::前缀明确指定datatable
})
# 在应用启动20秒后自动关闭
#observe({
#invalidateLater(200000, session)
#stopApp()
#})
}
# 运行应用
# 第二个应用的代码...
# 运行应用,指定端口号为5201
shinyApp(ui1, server1, options = list(port = 5201))
Shiny applications not supported in static R Markdown documents