Как получить данные / график для отображения в блестящем приложении?

  • Это мое первое блестящее приложение
  • Мой код, вероятно, ужасен, так как я впервые сделал что-то подобное
  • Я провел 3-4 дня, исследуя и пытаясь найти ответ
  • Я никогда раньше не пользовался этим форумом
  • Я очень близок к завершению, и эта последняя проблема меня убивает !! пожалуйста, помоги мне !!!

Мое блестящее приложение (для базы данных ставок на футбол) отлично работает локально и в браузере. Когда я загружаю его на сервер, я могу видеть его нормально, но он не загружает данные или график.

Пока я пробовал (безуспешно):

  1. добавление явных вызовов к пакетам (например, dplyr :: filter вместо просто filter)
  2. удаление вкладок и частей макета / приложения.
  3. удаление html-кода.
  4. добавление «shinyServer» и ввода, вывода, сеанса в программу на стороне сервера.
  5. перемещение вызовов в библиотеку (блестит) и т. д.
  6. изменение размера доступных данных (это не похоже на проблему с источником данных или размером данных)
  7. переустановил R, Rstudio и все соответствующие пакеты
  8. поместив файл data.csv в другую папку и соответственно изменив код
  9. изменил каталог данных на "/srv/shiny-server/FBC_Database_1819/Data/ResultsDatabase17.csv" в начале программы
  10. переустановленные инструменты / devtools
  11. Создан документ global.R, в котором библиотеки и фрейм данных сохранены как переменная RDS.
  12. изменил данные на файл .rds

    • НИЧТО ИЗ ЭТОГО НЕ РАБОТАЕТ ТАКОЕ ... ....

Мой код ниже:

    library(shiny)
    library(DT)
    library(dplyr)
    library(crosstalk)
    library(shinydashboard)

    FBC_Data <- read.csv("Data/ResultsDatabase17.csv", header = TRUE, stringsAsFactors = FALSE)

    Sys.setenv(TZ='GMT')
    Sys.time()

    FBC_Data$Date <- as.Date(FBC_Data$Date, "%d/%m/%Y")
    strftime(FBC_Data$Date, "%Y-%m-%d")
    format(FBC_Data$Date, "%Y-%m-%d")
    FBC_Data$Date <- gsub("0017", "2017", FBC_Data$Date)
    FBC_Data$Date <- gsub("0018", "2018", FBC_Data$Date)
    FBC_Data$Date <- as.Date(FBC_Data$Date)


    #START UI

    ui <- dashboardPage( skin = "yellow",
                 dashboardHeader(title = "THE FBC +2.5 DATABASE", titleWidth = 300),
                 dashboardSidebar(width = 300,
                                  sidebarMenu(
                                    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
                                    menuItem("Profits", tabName = "Profits", icon = icon("money")),




                                    # Select variable for y-axis 
                                    selectInput(inputId = "y", 
                                                label = "Y-axis:",
                                                choices = c("Odds for +2.5 goals" = "oddsovers",
                                                            "Home win odds" = "B365H", 
                                                            "Away win odds" = "B365A", 
                                                            "FBC Goal Rating" = "RATINGSSCORE",
                                                            "Actual Goals in Game" = "TotalGoals",
                                                            "Value" = "Value",
                                                            "Goals Scored per Game" = "Goalsscoredpg",
                                                            "Goals Concede Per Game" = "Goalsconcededpg",
                                                            "Total Goals Home" = "GoalstotalsH",
                                                            "Total Goals Away" = "GoalstotalsA",
                                                            "Over Two goals in games" = "Overtwogoals",
                                                            "+2.5 gls at home" = "OverglsdiffH",
                                                            "+2.5 gls away" = "OverglsdiffA",
                                                            "over three goals in games" = "overthreegls",
                                                            "Clean Sheets Home" = "CleansheetsH",
                                                            "Clean Sheets Away" = "CleansheetsA",
                                                            "Failed to score at home" = "FTSH",
                                                            "Failed to score away" = "FTSA",
                                                            "Failed to score at HT" = "FTSHT",
                                                            "BTTS percent" = "BTTSpercent",
                                                            "BTTS percent HOME" = "BTTSdiffH",
                                                            "BTTS percent AWAY" = "BTTSdiffa",
                                                            "Goal at HT percent" = "GoalHT",
                                                            "Clean Sheet at HT" = "CSHT",
                                                            "BTTS at HT" = "BTTSHT",
                                                            "Goals Per game Form" =" GoalsPGform",
                                                            "XG game total" = "Xgtotal",            
                                                            "XG week change" = "Xgchange",
                                                            "XGteam" = "Xgfor",
                                                            "XG opponent" ="XGagainst"), 
                                                selected = "RATINGSSCORE"),

                                    # Select variable for x-axis 
                                    selectInput(inputId = "x", 
                                                label = "X-axis:",
                                                choices = c("Odds for +2.5 goals" = "oddsovers",
                                                            "Home win odds" = "B365H", 
                                                            "Away win odds" = "B365A", 
                                                            "FBC Goal Rating" = "RATINGSSCORE",
                                                            "Actual Goals in Game" = "TotalGoals",
                                                            "Value" = "Value",
                                                            "Goals Scored per Game" = "Goalsscoredpg",
                                                            "Goals Concede Per Game" = "Goalsconcededpg",
                                                            "Total Goals Home" = "GoalstotalsH",
                                                            "Total Goals Away" = "GoalstotalsA",
                                                            "Over Two goals in games" = "Overtwogoals",
                                                            "+2.5 gls at home" = "OverglsdiffH",
                                                            "+2.5 gls away" = "OverglsdiffA",
                                                            "over three goals in games" = "overthreegls",
                                                            "Clean Sheets Home" = "CleansheetsH",
                                                            "Clean Sheets Away" = "CleansheetsA",
                                                            "Failed to score at home" = "FTSH",
                                                            "Failed to score away" = "FTSA",
                                                            "Failed to score at HT" = "FTSHT",
                                                            "BTTS percent" = "BTTSpercent",
                                                            "BTTS percent HOME" = "BTTSdiffH",
                                                            "BTTS percent AWAY" = "BTTSdiffa",
                                                            "Goal at HT percent" = "GoalHT",
                                                            "Clean Sheet at HT" = "CSHT",
                                                            "BTTS at HT" = "BTTSHT",
                                                            "Goals Per game Form" =" GoalsPGform",
                                                            "XG game total" = "Xgtotal",            
                                                            "XG week change" = "Xgchange",
                                                            "XGteam" = "Xgfor",
                                                            "XG opponent" ="XGagainst"), 
                                                selected = "TotalGoals"),

                                    # Select variable for color
                                    selectInput(inputId = "z", 
                                                label = "Color by:",
                                                choices = c("+2.5 odds" = "oddsovers", 
                                                            "Home win odds" = "B365H", 
                                                            "Away win odds" = "B365A", 
                                                            "FBC Goal Game Rating" = "RATINGSSCORE",
                                                            "BTTS" = "BTTS",
                                                            "Actual Goals in Game" = "TotalGoals"),
                                                selected = "+2.5 odds"),


                                    # Add a size numeric input
                                    numericInput("size", "Point size", 1, 1),


                                    img(src = "https://thefootballbetclub.files.wordpress.com/2016/07/02b_fbc_logo_url_neg.jpg", height = "200px")
                                  )
                 ),
                 ##BODY CONTENT - first page
                 dashboardBody(
                   tabItems(
                     # First tab content
                     tabItem(tabName = "dashboard",
                             # Boxes need to be put in a row (or column)
                             #add plot output
                             fluidRow(
                               tabBox(title = "Plots and Data", id = "tabset1", width = 12,
                                      tabPanel(title = "plot of games selected", plotOutput(outputId = "scatterplot")

                                      ),
                                      tabPanel(
                                        title = "Table of Selected Data", dataTableOutput("results")
                                      ),

                                      tabPanel(
                                        title = "Notes about this Database", htmlOutput("notesHTML")
                                      ),
                                      fluidRow(
                                        box(title = "Inputs", id = "inputbox1", width = 4,



                                            checkboxGroupInput("LeagueInput", "League",
                                                               choices = c("Prem" = "E0",
                                                                           "Champ" = "E1",
                                                                           "League1" = "E2",
                                                                           "League2" = "E3",
                                                                           "La Liga" = "SP1",
                                                                           "Bundasliga" = "D1",
                                                                           "Seria A"= "I1"), 
                                                               selected = c("E0", "E0", "E1", "E2", "E3", "SP1", "D1", "I1")),

                                            checkboxGroupInput("HomeAway", "Home or Away Teams",
                                                               choices = c("Home" = "H",
                                                                           "Away" = "A"),
                                                               selected = c("H", "A")),

                                            dateRangeInput("GameDates", "Choose Dates", start = "2017-04-04", end = "2018-05-13",
                                                           min = "2017-04-04", max = "2018-05-13", format = "yyyy-mm-dd",
                                                           startview = "month"),

                                            checkboxGroupInput("Month_select", "Month",
                                                               choices = c("September" = "September",
                                                                           "October" = "October",
                                                                           "November" = "November",
                                                                           "December" = "December",
                                                                           "January" = "January",
                                                                           "February" = "February",
                                                                           "March" = "March",
                                                                           "April" = "April",
                                                                           "May" = "May"),
                                                               selected = c("September", "October", "November", "December", "January", "February", "March", "April", "May")),

                                            sliderInput("CleansheetsH", "Clean Sheets at Home percent", min = 0, max = 1,
                                                        value = c(0, 1)),

                                            sliderInput("CleansheetsA", "Clean Sheets Away percent", min = 0, max = 1,
                                                        value = c(0, 1)),


                                            sliderInput("CSHT", "Kept a CLEAN SHEET by HALF TIME percent", min = 0.1, max = 1,
                                                        value = c(0.1, 1))

                                        ),
                                        box(title = "More Inputs", id = "inputbox2", width = 4,

                                            sliderInput("oddsInput", "B365 +2.5 odds for overs", min = 1, max = 3.2,
                                                        value = c(1, 3.2)),

                                            sliderInput("RATING_SCORE", "FBC Goal Rating", min = 0, max = 82.5,
                                                        value = c(0, 82.5)),

                                            sliderInput("GoalsscoredPG", "Goals Scored Per Game", min = 0, max = 3.5,
                                                        value = c(0, 3.7)),

                                            sliderInput("GoalsconcededPG", "Goals Conceded Per Game", min = 0, max = 3.1,
                                                        value = c(0, 3.1)),

                                            sliderInput("BTTSpercent", "BTTS percent", min = 0, max = 0.9,
                                                        value = c(0, 0.9)),

                                            sliderInput("BTTSHT", "BTTS by HALF TIME percent", min = 0, max = 0.6,
                                                        value = c(0, 0.6)),

                                            sliderInput("GoalTotalsH", "All Goals in matches at Home Per Game", min = 0, max = 5.3,
                                                        value = c(0, 5.3)),

                                            sliderInput("GoalTotalsA", "All Goals in matches Away Per Game", min = 0, max = 4.9,
                                                        value = c(0, 5)),

                                            sliderInput("Overtwogoals", "Over TWO goals per game percentage", min = 0, max = 1,
                                                        value = c(0, 1)),

                                            sliderInput("Overthreegoals", "Over THREE goals per game percentage", min = 0, max = 0.71,
                                                        value = c(0, 0.71))



                                        ),

                                        box(title = "Even More Inputs!", id = "inputbox3", width = 4,

                                            sliderInput("GoalsPGform", "Goals Per Game recent form (last 5 games) ", min = 0.5, max = 6.5,
                                                        value = c(0.5, 6.5)),

                                            sliderInput("Xgtotal", "XG Game Total (only for top Euro Leagues and Prem)", min = 0, max = 3.75,
                                                        value = c(0, 3.75)),

                                            sliderInput("Xgchange", "XG Game Total Difference from last game (only for top Euro Leagues and Prem)", min = -48, max = 49,
                                                        value = c(-48, 49)),

                                            sliderInput("Xgfor", "XG For last game (only for top Euro Leagues and Prem)", min = 0, max = 2.9,
                                                        value = c(0, 2.9)),

                                            sliderInput("XGagainst", "XG Against last game (only for top Euro Leagues and Prem)", min = 0, max = 2.4,
                                                        value = c(0, 2.4)),

                                            sliderInput("FTSH", "Failed to score at HOME percentage", min = 0, max = 1,
                                                        value = c(0, 1)),

                                            sliderInput("FTSA", "Failed to score AWAY percentage", min = 0, max = 1,
                                                        value = c(0, 1)),

                                            sliderInput("FTSHT", "Failed to score by HALF TIME percentage", min = 0, max = 1,
                                                        value = c(0, 1))
                                        )
                                      )

                               )
                             )
                     ),


                     # Second tab content
                     tabItem(tabName = "Profits",
                             h2("System Analysis"),
                             fluidRow(shiny::plotOutput(outputId = "plot"),
                                 actionButton("button", "Show Profit Earned over the period"),
                                 htmlOutput("testHTML")

                             )


                     )
                   )
                 )
)  

    #SERVER

    server <- function(input, output, session) {

    filtered_data <- reactive({
    FBC_Data %>% dplyr::filter(oddsovers >= input$oddsInput[1],
                    oddsovers <= input$oddsInput[2],
                    RATINGSSCORE >= input$RATING_SCORE[1],
                    RATINGSSCORE <= input$RATING_SCORE[2],
                    League %in%(input$LeagueInput),
                    HomeAway %in%(input$HomeAway),
                    Month %in%(input$Month_select),
                    CleansheetsH >= input$CleansheetsH[1],
                    CleansheetsH <= input$CleansheetsH[2],
                    CleansheetsA >= input$CleansheetsA[1],
                    CleansheetsA <= input$CleansheetsA[2],
                    BTTSpercent >= input$BTTSpercent[1],
                    BTTSpercent <= input$BTTSpercent[2],
                    BTTSHT >= input$BTTSHT[1],
                    BTTSHT <= input$BTTSHT[2],
                    CSHT >= input$CSHT[1],
                    CSHT <= input$CSHT[2],
                    Goalsscoredpg >= input$GoalsscoredPG[1],
                    Goalsscoredpg <= input$GoalsscoredPG[2],
                    Goalsconcededpg >= input$GoalsconcededPG[1],
                    Goalsconcededpg <= input$GoalsconcededPG[2],
                    GoalstotalsH >= input$GoalTotalsH[1],
                    GoalstotalsH <= input$GoalTotalsH[2],
                    GoalstotalsA >= input$GoalTotalsA[1],
                    GoalstotalsA <= input$GoalTotalsA[2],
                    Overtwogoals >= input$Overtwogoals[1],
                    Overtwogoals <= input$Overtwogoals[2],
                    overthreegls >= input$Overthreegoals[1],
                    overthreegls <= input$Overthreegoals[2],
                    FTSH >= input$FTSH[1],
                    FTSH <= input$FTSH[2],
                    FTSA >= input$FTSA[1],
                    FTSA <= input$FTSA[2],
                    FTSHT >= input$FTSHT[1],
                    FTSHT <= input$FTSHT[2],
                    GoalsPGform >= input$GoalsPGform[1],
                    GoalsPGform <= input$GoalsPGform[2],
                    Xgtotal >= input$Xgtotal[1],
                    Xgtotal <= input$Xgtotal[2],
                    Xgchange >= input$Xgchange[1],
                    Xgchange <= input$Xgchange[2],
                    Xgfor >= input$Xgfor[1],
                    Xgfor <= input$Xgfor[2],
                    XGagainst >= input$XGagainst[1],
                    XGagainst <= input$XGagainst[2],
                    between(Date,  input$GameDates[1], input$GameDates[2]))
  })


      observeEvent(input$button, {
       filtered_data2 <- filtered_data()
       filtered_data2$cumulative <- ifelse(filtered_data2$Overs == "TRUE", 1, -1)
       filtered_data2$cumulative2 <- ifelse(filtered_data2$cumulative == 1,         filtered_data2$oddsovers-1, -1)
     filtered_data2$cumulative3 <- cumsum(filtered_data2$cumulative2)
     profit_text1 <- tail(filtered_data2$cumulative3, n = 1)
     correct_results <- length(which(filtered_data2$Overs>="TRUE"))
    total_results <- length(which(filtered_data2$Overs>="FALSE"))
     profit_text2 <- round(correct_results / total_results, digits = 3)
winsprem <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("E0"))
winschamp <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("E1"))
winsleague1 <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("E2"))
winsleague2 <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("E3"))
winsspain <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("SP1"))
winsitaly <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("I1"))
winsgermany <- sum(filtered_data2$Overs>="TRUE" & filtered_data2$League %in% c("D1"))
Totalwins <- sum(winsprem, winschamp, winsleague1, winsleague2, winsspain, winsitaly, winsgermany)
winners <- dplyr::filter(filtered_data2, Overs %in% c("TRUE")) 
Return <- sum(winners$oddsovers)
Return
Profit <- Return-total_results
Profit
ROI <- round(Profit/total_results, digits = 2)
output$testHTML <- renderText(paste(" Your total profit for this system, (to £1 stakes),  would have been: ", "<b>", profit_text1, "</b>", "<br>", " It had a ", "<b>", profit_text2, "</b>", "% strike rate.", "<br>", " There were ", "<b>", Totalwins, "</b>", " winning +2.5 bets, out of ", "<b>", total_results, "</b>", "total results.", "<br>", "<b>", " Your ROI would have been ", ROI, " %", "</b>"))
output$plot <- renderPlot({
plot(filtered_data2$cumulative3, type = "l", lwd = "2",  main="System Profit Over Time",
     xlab="Games/Time", ylab="Profit", pch=18, col="blue")})
  })

    #OUTPUTS --

     output$results <- DT::renderDataTable({
     DT::datatable(newdata <- filtered_data())
     newdata[,c(1,2,3,4,5,6,7,8,11:14)]

  })  
      output$"notesHTML" <- renderText(paste(" Welcome .....", "<br>"))

     # GGPLOT
    require(ggplot2)
    require(shiny)

    output$scatterplot <- renderPlot({
    newdata_plot <- filtered_data()
    ggplot2::ggplot(newdata_plot, 
       aes_string(x = input$x, y = input$y, color = input$z)) +
      geom_point(size = input$size)+
      geom_smooth(method = "lm", se=T)
  })

}

shinyApp(ui = ui, server = server)

Вы уверены, что он правильно читает файл .csv? Он определенно правильно находит и загружает файл? Вы можете использовать shinyjs::logjs() для вывода на консоль браузера, чтобы убедиться, что они загружаются и обрабатываются правильно.

divibisan 13.09.2018 21:28

Это также поможет облегчить чтение вашего кода, если вы сделаете отступ правильно. В RStudio вы можете выбрать все, а затем перейти в меню: Code/Reindent Lines

divibisan 13.09.2018 21:29

да, извините за плохой отступ в коде, не знал, как сделать эту вещь кода / повторного перехода строк, спасибо. Также, когда я помещаю shinyjs :: logjs () в консоль, он говорит, что текст аргумента отсутствует. Не знаю, что это значит, но буду продолжать возиться

Greg Sloan 14.09.2018 14:52

Вы проверили, что файл .csv загружается? shinyjs::logjs() в основном эквивалент оператора print(), но он выводится на консоль браузера, поэтому работает на блестящем сервере. Вам нужно поместить в него текст или объект R, например: shinyjs::logjs(head(FBC_Data)). Вам также необходимо поместить useShinyjs(), в начало функции ui, просто внутри dashboardPage(, чтобы она работала.

divibisan 14.09.2018 17:00

спасибо за вашу помощь, но я пробовал это и до сих пор без радости

Greg Sloan 16.09.2018 13:38
0
5
269
1

Ответы 1

Моя проблема была связана с селекторами диапазона дат, как только я вынул:

                           between(Date,  input$GameDates[1], input$GameDates[2]))

немного кода, тогда он работал нормально.

нужно понять, почему это вызывало проблемы сейчас Благодарность

Другие вопросы по теме