Как предсказать модель lm на основе переменной, выбранной из выпадающего списка в Shiny App? - PullRequest
0 голосов
/ 17 февраля 2019

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

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

Изображение 1: где SNR используется из раскрывающегося списка

Изображение 2: где используется другая переменная (RSRP)

У меня возникли проблемы с первой возможностью получить шкалу ползунка (левая сторона) и ось X в моемзаговор для изменения в зависимости от выбора из выпадающего окна, однако я преодолел это с использованием conditionalPanel и установив условие на требуемый input.indepvar, пока это будет работать: предикат (fit, newdata = data.frame (SNR = varInput))
Это не будет выбирать Var <-input $ indepvar <br>прогнозировать (fit, newdata = data.frame (selectVar = varInput)) Даже при том, что распечатка selectVar дает SNR в результате (у меня естьэто выводится как тестовый вывод в конце).Я в основном хочу как-то заменить значение SNR на то, что выбрано из выпадающего меню (введите $ indepvar).Используемые данные взяты из папки пешеходов в этом наборе данных: http://www.cs.ucc.ie/~dr11/4G_Dataset/LTE_Dataset.zip

## Only run this example in interactive R sessions
if (interactive()) {
        shinyApp(
                ui <- fluidPage(
                        titlePanel("Regression Model (Dataset: pedestrian)"),
                        sidebarLayout(
                                sidebarPanel(
                                        selectInput("outcome", label = h3("Outcome"),
                                                    choices = list("DL_bitrate" = "DL_bitrate",
                                                                   "UL_bitrate" = "UL_bitrate",
                                                                   "RSSI" = "RSSI",
                                                                   "SNR" = "SNR",
                                                                   "RSRP" = "RSRP",
                                                                   "CQI" = "CQI"), selected = 1),

                                        selectInput("indepvar", label = h3("Explanatory variable"),
                                                    choices = list("SNR" = "SNR",
                                                                   "RSRP" = "RSRP",
                                                                   "RSRQ" = "RSRQ",
                                                                   "CQI" = "CQI",
                                                                   "ServingCell_Distance" = "ServingCell_Distance"), selected = 1),
                                        conditionalPanel(
                                                condition = "input.indepvar == 'SNR'",
                                                sliderInput("sliderIndVar",
                                                            label = "SNR Range:",
                                                            min = -10, max = 30, 5)
                                        ),
                                        conditionalPanel(
                                                condition = "input.indepvar == 'RSRP'",
                                                sliderInput("sliderIndVar",                # Plan on updating this but was working with SNR to start with 
                                                            label = "RSRP Range:",
                                                            min = -115, max = -65, 100)
                                        ),
                                        conditionalPanel(
                                                condition = "input.indepvar == 'RSRQ'",
                                                sliderInput("sliderIndVar",                # Plan on updating this but was working with SNR to start with 
                                                            label = "RSRQ Range:",
                                                            min = -18, max =-8, -12)
                                        ),
                                        conditionalPanel(
                                                condition = "input.indepvar == 'CQI'",
                                                sliderInput("sliderIndVar",                # Plan on updating this but was working with SNR to start with 
                                                            label = "CQI Range:",
                                                            min = 0, max = 15, 8)
                                        ),
                                        conditionalPanel(
                                                condition = "input.indepvar == 'ServingCell_Distance'",
                                                sliderInput("sliderIndVar",                # Plan on updating this but was working with SNR to start with 
                                                            label = "Serving Cell Distance:",
                                                            min = 150, max = 75000, 1000)
                                        )


                                ),

                                mainPanel(

                                        tabsetPanel(type = "tabs",

                                                    tabPanel("Scatterplot", plotOutput("scatterplot"),
                                                             h3("Slider Value:"), 
                                                             textOutput("text"),      # This show the select input from the slider for test purpose
                                                             h3("Predicted Value:"),  # This show the resultant prediction for test purpose
                                                             textOutput("pred1"),     # Works ok for SNR - as I've hard coded SNR in server model1pred  
                                                             h3("Select variable:"),  # This show the variable selected from the drop down 
                                                             textOutput("var1")),     # I want to use this variable as input to model1pred
                                                    tabPanel("Distribution", # Plots of distributions
                                                             fluidRow(
                                                                     column(6, plotOutput("distribution1")),
                                                                     column(6, plotOutput("distribution2")))
                                                    ),
                                                    tabPanel("Model Summary", verbatimTextOutput("summary")), # Regression output
                                                    tabPanel("Data", DT::dataTableOutput('tbl')) # Data as datatable

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

                        # Regression output
                        output$summary <- renderPrint({
                                fit <- lm(pedestrian[,input$outcome] ~ pedestrian[,input$indepvar])
                                names(fit$coefficients) <- c("Intercept", input$var2)
                                summary(fit)
                        })

                        # Prediction value
                        model1pred <- reactive({ 
                                varInput <- input$sliderIndVar
                                # selectVar<-input$indepvar                             # Was trying to use something like thi to replace SNR in prediction!!

                                predict(fit, newdata = data.frame(SNR = varInput))      # I want to replace SNR with which variable is selected from the 
                                # selectInput("indepvar" drop menu. 
                                #                predict(fit, newdata = data.frame(selectVar = varInput))      # This doesn't work for example 
                        })

                        # Data output
                        output$tbl = DT::renderDataTable({
                                DT::datatable(pedestrian, options = list(lengthChange = FALSE))
                        })


                        # Scatterplot output
                        output$scatterplot <- renderPlot({
                                varInput <- input$sliderIndVar                             # UPDATE HERE to be flexible with drop down menu!! 
                                plot(pedestrian[,input$indepvar], pedestrian[,input$outcome], main="Scatterplot",
                                     xlab=input$indepvar, ylab=input$outcome, pch=19)
                                abline(lm(pedestrian[,input$outcome] ~ pedestrian[,input$indepvar]), col="red")
                                lines(lowess(pedestrian[,input$indepvar],pedestrian[,input$outcome]), col="blue")
                                points(varInput, model1pred(), col = "red", pch = 16, cex = 2) 
                        }, height=400)


                        # Histogram output var 1
                        output$distribution1 <- renderPlot({
                                hist(pedestrian[,input$outcome], main="", xlab=input$outcome)
                        }, height=300, width=300)

                        # Histogram output var 2
                        output$distribution2 <- renderPlot({
                                hist(pedestrian[,input$indepvar], main="", xlab=input$indepvar)
                        }, height=300, width=300)

                        # Slider input & Prediction
                        output$text <- renderText({input$sliderIndVar}) 
                        # UPDATE HERE!!
                        output$pred1 <- renderText(model1pred())        # I want to also update the prediction based on the selection from the drop down menu
                        output$var1 <- renderText(input$indepvar)       # I can get this to update based on the 



                }
        )
}

Значение прогноза не обновляется, когда я выбираю что-либо, кроме SNR.

В результате моя прогнозируемая точка надиаграмма также не обновляется.Все остальное работает (масштаб оси, масштаб ползунка на основе выбранной входной переменной).Любые идеи будут высоко оценены.

1 Ответ

0 голосов
/ 17 февраля 2019

Если я не ошибаюсь, вы не можете использовать один и тот же inputId для всех ползунков.Только один из них будет доступен в качестве значения.Вы можете подтвердить это в print(input$sliderIndVar) внутри наблюдателя на сервере, чтобы удостовериться.

Я бы предложил назначить разные inputId для каждого ползунка.Например, sliderIndVarRSRP, sliderIndVarSNR и т. Д., А затем вызвать их на сервере с помощью input[[paste0("sliderIndVar", input$indepvar)]].Это должно указать, какой слайдер вы вызываете.

EDIT1: Что касается имени переменной в data.frame.

Так как вы хотите определить имя переменной в newdata какinput$indepvar, я могу думать только об изменении имени после создания data.frame, например:

varInput <- input$sliderIndVarWHATEVER
newdataInput <- data.frame(varInput)
colnames(newdataInput) <- input$indepvar
predict(fit, newdata = newdataInput)
...