Don't reinvent the wheel.  Use one of the existing libraries/packages for this.  For example Math::GSL, which is a binding to the GSL library.

The R-squared for a linear least squares fit of two vectors @$x, @$y (with x predicting y) can be computed as follows:

#!/usr/bin/perl -w use strict; use Math::GSL::Fit "gsl_fit_linear"; use Math::GSL::Statistics "gsl_stats_tss"; my $x = [1,2,3,4,5]; my $y = [5,7,8,12,13]; my $n = @$y; my ($status, $c0, $c1, $cov00, $cov01, $cov11, $ss_resid) = gsl_fit_linear($x, 1, $y, 1, $n); my $ss_total = gsl_stats_tss($y, 1, $n); print "SS residual = $ss_resid\n"; print "SS total = $ss_total\n"; my $R2 = 1 - $ss_resid / $ss_total; print "R^2 = $R2\n";
SS residual = 1.9 SS total = 46 R^2 = 0.958695652173913

If I'm understanding you correctly, you'd want to do this computation for every pair of lines.

(Note that for R^2 to be computable, there has to be some variance in the data to be predicted (as often with statistics).  In other words, $y = [2,2,2,2,2,2] wouldn't work, because here $ss_total would be 0, which would cause a division by zero error.)


In reply to Re: finding R-squared..please help by Eliya
in thread finding R-squared..please help by david_lyon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.