Function to calculate R2 (R-squared) in R

前端 未结 6 766
悲&欢浪女
悲&欢浪女 2020-11-27 15:59

I have a dataframe with observed and modelled data, and I would like to calculate the R2 value. I expected there to be a function I could call for this, but can\'t locate o

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 16:48

    Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]

    # 1. 'Actual' and 'Predicted' data
    df <- data.frame(
      y_actual = c(1:5),
      y_predicted  = c(0.8, 2.4, 2, 3, 4.8))
    
    # 2. R2 Score components
    
    # 2.1. Average of actual data
    avr_y_actual <- mean(df$y_actual)
    
    # 2.2. Total sum of squares
    ss_total <- sum((df$y_actual - avr_y_actual)^2)
    
    # 2.3. Regression sum of squares
    ss_regression <- sum((df$y_predicted - avr_y_actual)^2)
    
    # 2.4. Residual sum of squares
    ss_residuals <- sum((df$y_actual - df$y_predicted)^2)
    
    # 3. R2 Score
    r2 <- 1 - ss_residuals / ss_total
    

提交回复
热议问题