This doesn't seem quite right: assuming the model has an intercept, SStot 
is traditionally the sum of squares of the intercept only model (i.e., 
sumabs2(y 
- mean(y)). You can see this if you add a constant to the first column of dd, 
which should not change R^2 but instead results in an implausibly high 
value for random data. Two one-liners that should give correct results are:

r2 = 1-sumabs2(residuals(mod))/sumabs2(y - mean(y)) # or 
1-var(residuals(mod))/var(y)
adjr2 = 1-scale(mod, true)/var(y)

where y is the dependent variable and mod is the model. If the model is fit 
using a DataFrame, at least for now, adjr2 needs to be:

adjr2 = 1-scale(mod.model, true)/var(y)

Simon

On Wednesday, August 6, 2014 11:34:54 PM UTC-4, Taylor Maxwell wrote:
>
> I haven't seen code to do it yet but it is very simple to calculate with a 
> LinearModel from GLM  Below is some code to calculate r-squared or adjusted 
> r-squared from a linear model in GLM calculated from a dataframe or from a 
> model calculated without a data frame.  At the bottom is some simple code 
> to apply these functions.  It uses the Abs2Fun() from the NumericFuns 
> package to calculate the sum of squares quickly.
>
> using DataFrames
> using GLM
>
> import DataFrames.DataFrameRegressionModel
> import GLM.LinearModel
> import GLM.residuals
> using NumericFuns
>
>
> function 
> rsquared(mod::DataFrameRegressionModel{LinearModel{DensePredQR{Float64}},Float64})
> SStot=sum(Abs2Fun(),mod.model.rr.y)
> SSres=sum(Abs2Fun(),residuals(mod))
> return (1-(SSres/SStot))
> end
>
> function rsquared(mod::LinearModel{DensePredQR{Float64}})
> SStot=sum(Abs2Fun(),mod.rr.y)
> SSres=sum(Abs2Fun(),residuals(mod))
> return (1-(SSres/SStot))
> end
>
> function 
> adjrsquared(mod::DataFrameRegressionModel{LinearModel{DensePredQR{Float64}},Float64})
> SStot=sum(Abs2Fun(),mod.model.rr.y)
> SSres=sum(Abs2Fun(),residuals(mod))
> n=size(mod.model.rr.y,1)  #number of samples
> p=size(mod.mm.m,2)-1      #number of variables besides constant (assumes 
> intercept)
> return 1- ( (SSres/(n-p-1)) / (SStot/(n-1)) )
> end
>
> function adjrsquared(mod::LinearModel{DensePredQR{Float64}})
> SStot=sum(Abs2Fun(),mod.rr.y)
> SSres=sum(Abs2Fun(),residuals(mod))
> n=size(mod.rr.y,1)    #number of samples
> p=size(mod.pp.X,2)-1  #number of variables besides constant (assumes 
> intercept)
> return 1- ( (SSres/(n-p-1)) / (SStot/(n-1)) )
> end
>
>
> dd=randn(1000,7);
> df=convert(DataFrame,dd);
> aa=fit(LinearModel,x1~x2+x3+x4+x5+x6,df)
> bb=fit(LinearModel,aa.mm.m,aa.model.rr.y)
>
> rsquared(aa)
> adjrsquared(aa)
>
> rsquared(bb)
> adjrsquared(bb)
>
>
> On Wednesday, August 6, 2014 5:33:15 PM UTC-6, Jason Solack wrote:
>>
>> Hello everyone.  I am looking for a way to run this regression and 
>> retrieve the corresponding r squared value.  Is there a package out there 
>> that does this?
>>
>> Thank you for the help!
>>
>> Jason
>>
>

Reply via email to