Learn R Programming

MetricsWeighted (version 0.5.4)

r_squared: Generalized R-Squared

Description

Returns (weighted) proportion of deviance explained, see reference below. For the mean-squared error as deviance, this equals the usual (weighted) R-squared. The higher, the better.

Usage

r_squared(
  actual,
  predicted,
  w = NULL,
  deviance_function = mse,
  reference_mean = NULL,
  ...
)

Value

A numeric vector of length one.

Arguments

actual

Observed values.

predicted

Predicted values.

w

Optional case weights.

deviance_function

A positive (deviance) function taking four arguments: "actual", "predicted", "w" and "...".

reference_mean

An optional reference mean used to derive the null deviance. Recommended in out-of-sample applications.

...

Further arguments passed to weighted_mean and deviance_function.

Details

The deviance gain is calculated regarding the null model derived from the actual values. While fine for in-sample considerations, this is only an approximation for out-of-sample considerations. There, it is recommended to calculate null deviance regarding the in-sample (weighted) mean. This value can be passed by the argument reference_mean.

References

Cohen, Jacob. et al. (2002). Applied Multiple Regression/Correlation Analysis for the Behavioral Sciences (3rd ed.). Routledge. ISBN 978-0805822236.

See Also

deviance_normal, mse.

Examples

Run this code
r_squared(1:10, c(1, 1:9))
r_squared(1:10, c(1, 1:9), w = 1:10)
r_squared(0:2, c(0.1, 1, 2), deviance_function = deviance_poisson)
r_squared(0:2, c(0.1, 1, 2), w = rep(1, 3),
          deviance_function = deviance_poisson)
r_squared(0:2, c(0.1, 1, 2), w = rep(1, 3),
          deviance_function = deviance_tweedie, tweedie_p = 1)

# respect to 'own' deviance formula
myTweedie <- function(actual, predicted, w = NULL, ...) {
  deviance_tweedie(actual, predicted, w, tweedie_p = 1.5, ...)
}
r_squared(1:10, c(1, 1:9), deviance_function = myTweedie)

Run the code above in your browser using DataLab