[R] Rsquared in summary(lm)

Wataru Shito shito at seinan-gu.ac.jp
Fri May 10 03:24:12 CEST 2002


Hi, Wouter

Actually, I have a similar problem too with a simple regression.  
In my case, not only the R-square but also the estimates of intercept
and coefficient by lm() seem different from the calculation with the
well known formula for a simple regression.

What I used is the following code.  (I have just started to use R last
week so don't blame my inmature code, please!)
Simply,
  > ols1( y, x )
will give you the result of the simple regression.

Wouter, could you try the following code on your data and see whether
that's what you expect or not?

I will appreciate if anyone can give me some advice why this
differenct happens.

Thankk you.

Wataru Shito


-----------------------------------------

# Single Explanatory Variable Least Square Regression
#
library(methods)
# create ols class
setClass("ols", representation
         ( coefficients="list", standard.errors="list",
          r.square="numeric" ))
setMethod("show", "ols",
          function(object)
          {
            # create row names for data.frame
            rownames <- c("(Intercept)", "X")
            # create data.frame
            z <- data.frame( row.names=rownames,
                            Estimate=object at coefficients, Std.Error=object at standard.errors,
                            t.value=t.values )
            cat("\n")
            print(z)
            cat( "\nR-Square:", object at r.square, "\n\n" )
          }
          )

ols1 <- function( y, x ){
  size <- length(x) # number of ovservations
  xbar <- mean(x)
  ybar <- mean(y)
  Sxx <- sum( (x-xbar)^2 )
  b <- sum( (x-xbar)*(y-ybar) )/Sxx # coefficient
  a <- ybar - b*xbar # interception
  e <- y - a - b*x   # residuals
  # SSE (error sum of squares)
  SSE <- sum( e^2 )
  # SST (total sum of squares)
  SST <- sum( (y-ybar)^2 )
  # SSR (regression sum of squares)
  SSR <- b^2 * Sxx
  # Coefficient of determination
  r2 <- SSR / SST
  
  # unbiased estimator of sigma^2
  s.square <- sum(e^2)/(size - 2)
  # standard error for b
  std.error.b <- sqrt( s.square/Sxx )
  # standard error for intercept
  std.error.a <- sqrt( s.square*(1/size + xbar^2/Sxx) )
  standard.errors <- list( intercept=std.error.a, coeficient=std.error.b )
  coefficients <- list( intercept=a, coefficient=b )
  new("ols", coefficients=coefficients, standard.errors=standard.errors, r.square=r2 )
}
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list