coefficient of determination

rsq.numeric R Documentation

Description

The rsq()-function calculates the \(R^2\), the coefficient of determination, between the ovserved and predicted <numeric> vectors. By default rsq() returns the unadjusted \(R^2\). For adjusted \(R^2\) set \(k = \kappa - 1\), where \(\kappa\) is the number of parameters.

Usage

## S3 method for class 'numeric'
rsq(actual, predicted, k = 0, ...)

## S3 method for class 'numeric'
weighted.rsq(actual, predicted, w, k = 0, ...)

rsq(...)

weighted.rsq(...)

Arguments

actual

A <numeric>-vector of length \(n\). The observed (continuous) response variable.

predicted

A <numeric>-vector of length \(n\). The estimated (continuous) response variable.

k

A <numeric>-vector of length 1 (default: 0). If \(k>`0\) the function returns the adjusted \(R^2\).

Arguments passed into other methods.

w

A <numeric>-vector of length \(n\). The weight assigned to each observation in the data.

Value

A <numeric> vector of length 1.

Calculation

The metric is calculated as follows,

\[ R^2 = 1 - \frac{\text{SSE}}{\text{SST}} \frac{n-1}{n - (k + 1)} \]

Where \(\text{SSE}\) is the sum of squared errors, \(\text{SST}\) is total sum of squared errors, \(n\) is the number of observations, and \(k\) is the number of non-constant parameters.

Examples

# 1) fit a linear
# regression
model <- lm(
  mpg ~ .,
  data = mtcars
)

# 1.1) define actual
# and predicted values
# to measure in-sample performance
actual    <- mtcars$mpg
predicted <- fitted(model)

# 2) calculate performance
# using R squared adjusted and
# unadjused for features
cat(
  "Rsq", rsq(
    actual    = actual,
    predicted = fitted(model)
  ),
  "Rsq (Adjusted)", rsq(
    actual    = actual,
    predicted = fitted(model),
    k = ncol(model.matrix(model)) - 1
  ),
  sep = "\n"
)