我有一个问题,作为R和编程的新手,总的来说,我需要您的帮助。
Q1)第一个问题是,如果您查看我的代码,我正在尝试在我的SHINY选项卡中的一个上运行GIF,但它不起作用。这是我在APP选项卡上看到的错误:“ $运算符对于原子向量无效”,我看到了一些类似的帖子,但它们与GIF无关。
我几乎花了一个星期尝试所有事情。我似乎无法弄清楚这两个问题。该GIF可以完美独立地运行,但是当我将其与Shiny合并时,会出现上述错误。
UI:
df <- read.csv("C:/Users/XXX/Downloads/movie1.csv")
df1 <- read.csv("C:/Users/XXX/Downloads/movie2.csv")
library(gifski)
library(gganimate)
library(dplyr)
library(DT)
library(shinythemes)
library(scales)
library(shiny)
library(ggplot2)
library(plotly)
n_total <- nrow(df)
ui <- fluidPage(theme = shinytheme("united"),
titlePanel("Movie browser, 1960 - 2014", windowTitle = "Movies"),
# Sidebar layout with a input and output definitions
sidebarLayout(
# Inputs
sidebarPanel(
wellPanel(
# Select variable for y-axis
selectInput(inputId = "y",
label = h4("Y-axis:"),
choices =c("Budget" ="budget", "Revenue" = "revenue", "Runtime" = "runtime", "Vote average" = "vote_average", "Year released" = "release_year", "Profit" = "breakeven"),
selected = "revenue"),
# Select variable for x-axis
selectInput(inputId = "x",
label = h4("X-axis:"),
choices = c("Budget" ="budget", "Revenue" = "revenue", "Runtime" = "runtime", "Vote average" = "vote_average", "Year released" = "release_year", "Profit" = "breakeven"),
selected = "budget")),
selectInput(inputId = "z",
label = h4("By Color:"),
choices = c("Genre" = "genre", "Average Votes" = "AerageVotesCat")),
# Set alpha level
sliderInput(inputId = "alpha",
label = h4("Alpha:"),
min = 0, max = 1,
value = 0.5),
sliderInput("SectorTime", h4("Select a time period:"), min = 1960, max = 2015,
value = c(1960,2015), step = 5),
textInput("Director", h4("Director name contains (e.g., Miyazaki)")),
numericInput(inputId = "n",
label = h4("Sample size:"),
value = 30,
min = 1, max = n_total,
step = 1),
radioButtons(inputId = "filetype",
label = "Select filetype:",
choices = c("csv", "tsv"),
selected = "csv"),
# Select variables to download
checkboxGroupInput(inputId = "selected_var",
label = "Select variables:",
choices = names(df),
selected = c("title"))
),
# Outputs
mainPanel(
tabsetPanel(
tabPanel(h4("PLOT"), plotlyOutput("plot"),
h4(textOutput(outputId = "correlation"))),
tabPanel(h4("Dynamic Viz"), plotlyOutput("plot1") ),
tabPanel(h4("Gif Viz"), imageOutput("plot2")),
tabPanel(h4("DATA"), DT::dataTableOutput(outputId = "moviestable"),
HTML("Select filetype and variables, then hit 'Download data'."),
br(), br(), # line break and some visual separation
downloadButton("download_data", "Download data")))
)
)
)
SERVER:
# Define server function required to create the scatterplot
server <- function(input, output) {
dataset <- reactive({
df[sample(nrow(df), input$SectorTime),]
})
# Create scatterplot object the plotOutput function is expecting
output$plot <- renderPlotly({
point <- format_format(big.mark = " ", decimal.mark = ",", scientific = FALSE)
p <- ggplot(data = dataset(), aes_string(x = input$x, y = input$y, col = input$z)) +
geom_point(alpha = input$alpha, size = 2, shape = 1) + theme_minimal() +
ggtitle("Scatter plot between various variables") +scale_x_continuous(labels = point) + scale_y_continuous(labels = point)
p + theme(axis.text.x = element_text(angle = 30))
})
output$correlation <- renderText({
r <- round(cor(df[, input$x], df[, input$y], use = "pairwise"), 3)
paste0("Correlation = ", r, ". Note: If the relationship between the two variables is not linear, the correlation coefficient will not be meaningful.")
})
output$plot1 <- renderPlotly({
df %>%
plot_ly(x = ~budget, y = ~revenue, width = 1000, height = 700) %>%
add_markers(size = ~runtime, color = ~genre,
frame = ~release_year, ids = ~id,marker = list(sizemode = "diameter"))
})
output$moviestable <- DT::renderDataTable({
movies_sample <- df %>%
sample_n(input$n) %>%
select(title: AerageVotesCat)
DT::datatable(data = movies_sample,
options = list(pageLength = 10),
rownames = FALSE)
})
**output$plot2 <- renderImage({
df2 <- df1 %>%
group_by(release_year) %>%
# The * 1 makes it possible to have non-integer ranks while sliding
mutate(rank = rank(-revenue),
Value_rel = revenue/revenue[rank==1],
Value_lbl = paste0(" ",round(revenue))) %>%
group_by(title) %>%
filter(rank <=10) %>%
ungroup()
staticplot = ggplot(df2, aes(rank, group = title,
fill = as.factor(title), color = as.factor(title))) +
geom_tile(aes(y = revenue/2,
height = revenue,
width = 0.9), alpha = 0.8, color = NA) +
geom_text(aes(y = 0, label = paste(title, " ")), vjust = 0.2, hjust = 1) +
geom_text(aes(y=revenue,label = Value_lbl, hjust=0)) +
coord_flip(clip = "off", expand = FALSE) +
scale_y_continuous(labels = scales::comma) +
scale_x_reverse() +
guides(color = FALSE, fill = FALSE) +
theme(axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.position="none",
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.grid.major.x = element_line( size=.1, color="grey" ),
panel.grid.minor.x = element_line( size=.1, color="grey" ),
plot.title=element_text(size=25, hjust=0.5, face="bold", colour="grey", vjust=-1),
plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="grey"),
plot.caption =element_text(size=8, hjust=0.5, face="italic", color="grey"),
plot.background=element_blank(),
plot.margin = margin(2,2, 2, 4, "cm"))
anim = staticplot + transition_states(release_year, transition_length = 4, state_length = 1) +
view_follow(fixed_x = TRUE) +
labs(title = 'Revenue ($) per Year for the top 10 movies : {closest_state}',
subtitle = "Top 10 Movies",
caption = "Revenue in USD | Data Source: Kaggle")
animate(anim, 200, fps = 4, width = 800, height = 900)
})**
output$download_data <- downloadHandler(
filename = function() {
paste0("df.", input$filetype)
},
content = function(file) {
if(input$filetype == "csv"){
write_csv(df %>% select(input$selected_var), path = file)
}
if(input$filetype == "tsv"){
write_tsv(df %>% select(input$selected_var), path = file)
}
}
)
}
# Create the Shiny app object
shinyApp(ui = ui, server = server)