Search code examples
rshinyshiny-server

Use a reactive dataframe in Shiny to predict(svm)


I wanted to create an interactive Shiny app where users could input values for a dataframe, and then it would apply that dataframe to a predict in an svm, giving the output of the prediction based on the given values. However, I can't seem to figure out how to save a reactive in the format that I can apply to the predict function. Can anyone help me?

My server.R file:

library(e1071)

X1 <- runif(100)
X2<- runif(100)          
Y <-runif(100) 
df <-data.frame(Y,X1,X2)

svm(Y~X1+X2, data=df, probability=TRUE)

svm.test<-svm(Y~X1+X2, data=df, probability=TRUE)




library("shiny")
shinyServer(
function(input,output,session){

tableStart <- data.frame(X1=4, X2=6)

newEntry <- reactive({
  input$update
  newLine <- isolate(data.frame(X1=input$X1, X2=input$X2))
})
output$table1 <- renderTable({rbind(tableStart, newEntry())})


predictions<-predict(svm.test, newEntry, probability=TRUE)    

My ui.R file:

library("shiny")    
shinyUI(pageWithSidebar(headerPanel("Adding entries to table"),
                    sidebarPanel( sliderInput("X1", 
                                              label = "X1:",
                                              min = 0, max = 10, value = 0),

                                  sliderInput("X2", 
                                              label = "X2:",
                                              min = 0, max = 10, value = 0),
                                 actionButton("update", "Update Table")),
                    mainPanel(tableOutput("table1"))))

Any help you all can give me on how to save the output as a data.frame or vector that can be used in the predict function would be greatly appreciated.

Thanks!

Edited to reflect the omission noted in the first answer.


Solution

  • I think I found the answer on Hack-R's github (which I found from a search here).

    https://github.com/hack-r/coursera_shiny

    I don't really understand the code, but I think I can cannibalize it to my full example. Thanks to user1269942 for the help, and to Hack-R for posting his finished product on git.

    output$text <- renderPrint({
      {  ds1        <- values$df 
      a <- predict(svm.test, newdata = data.frame(ds1))
      names(a) <- NULL
      cat(a)
    
      }
    })