## S3 method for class 'numeric'
rsq(actual, predicted, k = 0, ...)
## S3 method for class 'numeric'
weighted.rsq(actual, predicted, w, k = 0, ...)
## Generic S3 method
rsq(
...,k = 0
)
## Generic S3 method
weighted.rsq(
...,
w,k = 0
)
Coefficient of Determination
rsq.numeric | R Documentation |
Description
A generic function for the \(R^2\). The unadjusted \(R^2\) is returned by default. Use weighted.rsq()
for the weighted \(R^2\).
Usage
Arguments
actual
|
A |
predicted
|
A |
k
|
A |
…
|
Arguments passed into other methods. |
w
|
A |
Value
A <numeric>
vector of length 1.
Definition
Let \(R^2 \in [-\infty, 1]\) be the explained variation. The \(R^2\) is calculated as,
\[ R^2 = 1 - \frac{\sum{(y_i - \hat{y}_i)^2}}{\sum{(y_i-\bar{y})^2}} \frac{n-1}{n - (k + 1)} \]
Where:
-
\(n\) is the number of observations
-
\(k\) is the number of features
-
\(y\) is the actual values
-
\(\hat{y}_i\) is the predicted values
-
\(\sum{(y_i - \hat{y}_i)^2}\) is the sum of squared errors and,
-
\(\sum{(y_i-\bar{y})^2}\) is total sum of squared errors
Examples
# 1) fit a linear
# regression
<- lm(
model ~ .,
mpg data = mtcars
)
# 1.1) define actual
# and predicted values
# to measure in-sample performance
<- mtcars$mpg
actual <- fitted(model)
predicted
# 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"
)