Using shiny for simple regression model.

Using the LM function in shiny.

Marcos de Aguiar
Software Developer

The app.

  • Great web application using shiny.

  • Receives 4 numbers as input.

  • On the inside it makes a linear fit with the x vector 1:4

  • It then shows the slope and the intercep of the numbers.

  • Can be used as an example for the use of the lm function.

The UI code:

library(shiny)
shinyUI(
  pageWithSidebar(
    headerPanel("Linear model slope and intercept."),
    sidebarPanel(
      numericInput('firstNumber', '1st Number', 19),
      numericInput('secondNumber', '2nd Number', 20),
      numericInput('thirdNumber', '3rd Number', 21),
      numericInput('fourthNumber', '4th Number', 22),
      ##actionButton("goButton", "Go!")
      submitButton('Submit')
    ),
    mainPanel(
      h3('Results of of the fit'),
      h4('Slope'),
      verbatimTextOutput("slope"),
      h4('Intercept'),
      verbatimTextOutput("intercept")
    )
  )
)

The Server code:

library(shiny)

getSlope <- function(y1, y2, y3, y4)
{
  y <- c(y1, y2, y3, y4)
  x <- 1:4
  ds <- data.frame(y, x)
  fit <- lm(y ~ x, data = ds)
  cf1 <- summary(fit)$coefficients
  cf1[2,1]
}

getIntercept <- function(y1, y2, y3, y4)
{
  y <- c(y1, y2, y3, y4)
  x <- 1:4
  ds <- data.frame(y, x)
  fit <- lm(y ~ x, data = ds)
  cf1 <- summary(fit)$coefficients
  cf1[1,1]
}

shinyServer(
  function(input, output) {

    output$slope <- renderText({ y1 <- input$firstNumber
                                 y2 <- input$secondNumber
                                 y3 <- input$thirdNumber
                                 y4 <- input$fourthNumber
                                 getSlope(y1, y2, y3, y4)})

The Server code (cont.):

shinyServer(
  function(input, output) {

    output$slope <- renderText({ y1 <- input$firstNumber
                                 y2 <- input$secondNumber
                                 y3 <- input$thirdNumber
                                 y4 <- input$fourthNumber
                                 getSlope(y1, y2, y3, y4)})


   output$intercept <- renderText({y1 <- input$firstNumber
                                   y2 <- input$secondNumber
                                   y3 <- input$thirdNumber
                                   y4 <- input$fourthNumber
                                   getIntercept(y1, y2, y3, y4)})
  }
)

Conclusions:

  • The app can be used to find the slopes and intercept.

  • Users can expand on it to include more sophisticated analysis, and change the X values as well.