library(shiny)

ui = fluidPage(
  titlePanel("Manual Linear Regression"),
  
  sidebarLayout(
    sidebarPanel(
      fileInput("datafile", "Upload a file with 2 cols"),
      numericInput("mu", "Null value for slope", value = 0),
      selectInput("alt", "Alternative Hypothesis",
                  choices = c("two-sided", "less", "greater")),
      numericInput("conf", "Confidence Level (%)", value = 95),
      actionButton("go", "Run Regression")
    ),
    
    mainPanel(
      plotOutput("plot"),
      verbatimTextOutput("output")
    )
  )
)

server = function(input, output) {
  
  observeEvent(input$go, {
    
    req(input$datafile)
    dat = read.csv(input$datafile$datapath)
    
    x = dat[[1]]
    y = dat[[2]]
    
    if(!is.numeric(x) | !is.numeric(y)){
      stop("x and y hafta be numeric")
    }
    if(length(x)!=length(y)){
      stop("x and y hafta be same length")
    }
    if(is.matrix(x) | is.data.frame(x)){
      stop("only one explanatory variable allowed")
    }
    
    n = length(x)
    xbar = mean(x)
    ybar = mean(y)
    
    b1 = sum((x - xbar)*(y - ybar)) / sum((x - xbar)^2)
    b0 = ybar - b1*xbar
    
    yhat = b0 + b1*x
    resid = y - yhat
    sse = sum(resid^2)
    
    seb1 = sqrt(sse / (n - 2)) / sqrt(sum((x - xbar)^2))
    tstat = (b1 - input$mu) / seb1
    
    if(input$alt == "two-sided"){
      pval = 2*(1 - pt(abs(tstat), df = n - 2))
    } else if(input$alt == "less"){
      pval = pt(tstat, df = n - 2)
    } else {
      pval = 1 - pt(tstat, df = n - 2)
    }
    
    alpha = 1 - input$conf/100
    tcrit = qt(1 - alpha/2, df = n - 2)
    cilow = b1 - tcrit*seb1
    cihigh = b1 + tcrit*seb1
    
    output$output = renderPrint({
      cat("intercept =", round(b0, 4), "")
      cat("slope =", round(b1, 4), "")
      cat("sse =", round(sse, 4), "")
      cat("residuals: ")
      print(round(resid, 4))
      cat("t-stat =", round(tstat, 4), "")
      cat("p-value =", format.pval(pval, digits = 4), "")
      cat("conf int for slope (", input$conf, "%): [",
          round(cilow, 4), ", ", round(cihigh, 4), "]", sep = "")
    })
    
    output$plot = renderPlot({
      plot(x, y, main = "Simple Linear Regression", xlab = "x", ylab = "y")
      abline(a = b0, b = b1, col = 2, lwd = 2)
    })
  })
}

shinyApp(ui = ui, server = server)
Shiny applications not supported in static R Markdown documents