tests/testthat/test-linreg-estimation-predicted.R

#' ---
#' title: "Tests: The Linear Regression Model (Predicted)"
#' author: "Ivan Jacob Agaloos Pesigan"
#' date: "`r Sys.Date()`"
#' output: rmarkdown::html_vignette
#' vignette: >
#'   %\VignetteIndexEntry{Tests: The Linear Regression Model (Predicted)}
#'   %\VignetteEngine{knitr::rmarkdown}
#'   %\VignetteEncoding{UTF-8}
#' ---
#'
#+ include = FALSE
knitr::opts_chunk$set(
  error = TRUE,
  collapse = TRUE,
  comment = "#>",
  out.width = "100%"
)
#'
#'
# The Linear Regression Model: Predicted Values {#linreg-estimation-predicted-example}
#'
#+ echo = FALSE
library(testthat)
library(jeksterslabRlinreg)
#'
#' ## Data
#'
#' See `jeksterslabRdatarepo::wages.matrix()` for the data set used in this example.
#'
#+
X <- jeksterslabRdatarepo::wages.matrix[["X"]]
# age is removed
X <- X[, -ncol(X)]
y <- jeksterslabRdatarepo::wages.matrix[["y"]]
head(X)
head(y)
#'
#' ## $\mathrm{Py}$
#'
#+
Pmatrix <- P(X = X)
betahat <- betahat(
  X = X,
  y = y
)
result_Py1 <- .Py(
  y = y,
  P = Pmatrix
)
result_Py2 <- .Py(
  y = y,
  X = X
)
result_Py3 <- Py(
  X = X,
  y = y
)
#'
#' ## $\mathrm{X} \hat{\boldsymbol{\beta}}$
#'
#+
result_Xbetahat1 <- .Xbetahat(
  X = X,
  y = y
)
result_Xbetahat2 <- .Xbetahat(
  X = X,
  betahat = betahat
)
result_Xbetahat3 <- Xbetahat(
  X = X,
  y = y
)
#'
#' ## $\hat{\mathrm{y}}$
#'
#+
result_yhat <- yhat(
  X = X,
  y = y
)
#'
#' ## `lm()` function
#'
#+
lmobj <- lm(
  wages ~ gender + race + union + education + experience,
  data = jeksterslabRdatarepo::wages
)
lm_yhat <- as.vector(predict(lmobj))
#'
#'
#+
context("Test linreg-estimation-projection")
test_that("Py = yhat.", {
  expect_equivalent(
    length(result_Py1),
    length(result_Py2),
    length(result_Py3),
    length(result_Xbetahat1),
    length(result_Xbetahat2),
    length(result_Xbetahat3),
    length(result_yhat),
    length(lm_yhat)
  )
  for (i in seq_along(result_Py1)) {
    expect_equivalent(
      result_Py1[i],
      lm_yhat[i]
    )
  }
  for (i in seq_along(result_Py2)) {
    expect_equivalent(
      result_Py2[i],
      lm_yhat[i]
    )
  }
  for (i in seq_along(result_Py3)) {
    expect_equivalent(
      result_Py3[i],
      lm_yhat[i]
    )
  }
  for (i in seq_along(result_Xbetahat1)) {
    expect_equivalent(
      result_Xbetahat1[i],
      lm_yhat[i]
    )
  }
  for (i in seq_along(result_Xbetahat2)) {
    expect_equivalent(
      result_Xbetahat2[i],
      lm_yhat[i]
    )
  }
  for (i in seq_along(result_Xbetahat3)) {
    expect_equivalent(
      result_Xbetahat3[i],
      lm_yhat[i]
    )
  }
  for (i in seq_along(result_yhat)) {
    expect_equivalent(
      result_yhat[i],
      lm_yhat[i]
    )
  }
})
test_that("error.", {
  expect_error(
    .Py(
      y = y
    )
  )
  expect_error(
    .Xbetahat(
      X = X
    )
  )
})
jeksterslabds/jeksterslabRlinreg documentation built on Jan. 7, 2021, 8:30 a.m.