Statis...:Sparse(3pm)
π¦ Statistics::Descriptive(3pm) π¦
okay so bestie, welcome to the Statistics::Descriptive manpage β it's giving basic descriptive statistical functions and honestly it's a whole vibe. lowkey essential, no cap. π
π NAME π
Statistics::Descriptive β module of basic descriptive statistical functions. periodt.
β¨ VERSION β¨
version 3.0801 β iconic. π
πΈ SYNOPSIS πΈ
use Statistics::Descriptive;
my $stat = Statistics::Descriptive::Full->new();
$stat->add_data(1,2,3,4);
my $mean = $stat->mean();
my $var = $stat->variance();
my $tm = $stat->trimmed_mean(.25);
$Statistics::Descriptive::Tolerance = 1e-10;
π« DESCRIPTION π«
This module provides basic functions used in descriptive statistics. It has an object oriented design and supports two different types of data storage and calculation objects: sparse and full. With the sparse method, none of the data is stored and only a few statistical measures are available. Using the full method, the entire data set is retained and additional functions are available.
Whenever a division by zero may occur, the denominator is checked to be greater than the value $Statistics::Descriptive::Tolerance, which defaults to 0.0. You may want to change this value to some small positive value such as 1e-24 in order to obtain error messages in case of very small denominators. π«Ά
Many of the methods (both Sparse and Full) cache values so that subsequent calls with the same arguments are faster. slay. β
π METHODS π
β¨ Sparse Methods β¨
$stat = Statistics::Descriptive::Sparse->new();β Create a new sparse statistics object.$stat->clear();β Effectively the same as:
my $class = ref($stat);
undef $stat;
$stat = new $class;
except more efficient.
$stat->add_data(1,2,3);β Adds data to the statistics variable. The cached statistical values are updated automatically.$stat->count();β Returns the number of data items.$stat->mean();β Returns the mean of the data.$stat->sum();β Returns the sum of the data.$stat->variance();β Returns the variance of the data. Division by n-1 is used.$stat->standard_deviation();β Returns the standard deviation of the data. Division by n-1 is used.$stat->min();β Returns the minimum value of the data set.$stat->mindex();β Returns the index of the minimum value of the data set.$stat->max();β Returns the maximum value of the data set.$stat->maxdex();β Returns the index of the maximum value of the data set.$stat->sample_range();β Returns the sample range (max - min) of the data set.
π Full Methods π
Similar to the Sparse Methods above, any Full Method that is called caches the current result so that it doesn't have to be recalculated. In some cases, several values can be cached at the same time. π§
$stat = Statistics::Descriptive::Full->new();β Create a new statistics object that inherits fromStatistics::Descriptive::Sparseso that it contains all the methods described above.$stat->add_data(1,2,4,5);β Adds data to the statistics variable. All of the sparse statistical values are updated and cached. Cached values from Full methods are deleted since they are no longer valid.
Note: Calling add_data with an empty array will delete all of your Full method cached values! Cached values for the sparse methods are not changed.
$stat->add_data_with_samples([{1 => 10}, {2 => 20}, {3 => 30},]);β Add data to the statistics variable and set the number of samples each value has been built with. The data is the key of each element of the input array ref, while the value is the number of samples:[{data1 => smaples1}, {data2 => samples2}, ...].
NOTE: The number of samples is only used by the smoothing function and is ignored otherwise. It is not equivalent to repeat count. In order to repeat a certain datum more than one time call add_data() like this:
my $value = 5;
my $repeat_count = 10;
$stat->add_data(
[ ($value) x $repeat_count ]
);
$stat->get_data();β Returns a copy of the data array.$stat->get_data_without_outliers();β Returns a copy of the data array without outliers. The minimum number of samples to apply the outlier filtering is$Statistics::Descriptive::Min_samples_number,4by default.
A function to detect outliers needs to be defined (see "set_outlier_filter"), otherwise the function will return an undef value.
The filtering will act only on the most extreme value of the data set (i.e.: value with the highest absolute standard deviation from the mean).
If there is the need to remove more than one outlier, the filtering needs to be re-run for the next most extreme value with the initial outlier removed.
This is not always needed since the test (for example Grubb's test) usually can only detect the most extreme value. If there is more than one extreme case in a set, then the standard deviation will be high enough to make neither case an outlier.
$stat->set_outlier_filter($code_ref);β Set the function to filter out the outlier.
$code_ref is the reference to the subroutine implementing the filtering function.
Returns "undef" for invalid values of $code_ref (i.e.: not defined or not a code reference), 1 otherwise.
- Example #1: Undefined code reference
my $stat = Statistics::Descriptive::Full->new();
$stat->add_data(1, 2, 3, 4, 5);
print $stat->set_outlier_filter(); # => undef
- Example #2: Valid code reference
sub outlier_filter { return $_[1] > 1; }
my $stat = Statistics::Descriptive::Full->new();
$stat->add_data( 1, 1, 1, 100, 1, );
print $stat->set_outlier_filter( \&outlier_filter ); # => 1
my @filtered_data = $stat->get_data_without_outliers();
# @filtered_data is (1, 1, 1, 1)
In this example the series is really simple and the outlier filter function as well. For more complex series the outlier filter function might be more complex (see Grubbs' test for outliers).
The outlier filter function will receive as first parameter the Statistics::Descriptive::Full object, as second the value of the candidate outlier. Having the object in the function might be useful for complex filters where statistics properties are needed (again see Grubbs' test for outlier).
$stat->set_smoother({ method => 'exponential', coeff => 0, });β Set the method used to smooth the data and the smoothing coefficient. See"Statistics::Smoother"for more details.$stat->get_smoothed_data();β Returns a copy of the smoothed data array.
The smoothing method and coefficient need to be defined (see "set_smoother"), otherwise the function will return an undef value.
$stat->sort_data();β Sort the stored data and update themindexandmaxdexmethods. This method uses perl's internal sort.$stat->presorted(1);$stat->presorted();β If called with a non-zero argument, this method sets a flag that says the data is already sorted and need not be sorted again. Since some of the methods in this class require sorted data, this saves some time. If you supply sorted data to the object, call this method to prevent the data from being sorted again. The flag is cleared wheneveradd_datais called. Calling the method without an argument returns the value of the flag.$stat->skewness();β Returns the skewness of the data. A value of zero is no skew, negative is a left skewed tail, positive is a right skewed tail. This is consistent with Excel.$stat->kurtosis();β Returns the kurtosis of the data. Positive is peaked, negative is flattened.$x = $stat->percentile(25);($x, $index) = $stat->percentile(25);β Sorts the data and returns the value that corresponds to the percentile as defined in RFC2330:
- For example, given the 6 measurements:-2, 7, 7, 4, 18, -5ThenF(-8) = 0,F(-5) = 1/6,F(-5.0001) = 0,F(-4.999) = 1/6,F(7) = 5/6,F(18) = 1,F(239) = 1. Note that we can recover the different measured values and how many times each occurred fromF(x)-- no information regarding the range in values is lost. Summarizing measurements using histograms, on the other hand, in general loses information about the different values observed, so the EDF is preferred. Using either the EDF or a histogram, however, we do lose information regarding the order in which the values were observed. Whether this loss is potentially significant will depend on the metric being measured. We will use the term "percentile" to refer to the smallest value of x for whichF(x) >= a given percentage. So the 50th percentile of the example above is 4, sinceF(4) = 3/6 = 50%; the 25th percentile is -2, sinceF(-5) = 1/6 < 25%, andF(-2) = 2/6 >= 25%; the 100th percentile is 18; and the 0th percentile is -infinity, as is the 15th percentile, which for ease of handling and backward compatibility is returned asundef()by the function. Care must be taken when using percentiles to summarize a sample, because they can lend an unwarranted appearance of more precision than is really available. Any such summary must include the sample size N, because any percentile difference finer than1/Nis below the resolution of the sample. (Taken from: RFC2330 - Framework for IP Performance Metrics, Section 11.3. Defining Statistical Distributions. RFC2330 is available from: <http://www.ietf.org/rfc/rfc2330.txt> .)
If the percentile method is called in a list context then it will also return the index of the percentile.
$x = $stat->quantile($Type);β Sorts the data and returns estimates of underlying distribution quantiles based on one or two order statistics from the supplied elements.
This method uses the same algorithm as Excel and R language (quantile type 7).
The generic function quantile produces sample quantiles corresponding to the given probabilities.
$Type is an integer value between 0 to 4 :
0β zero quartile (Q0) : minimal value1β first quartile (Q1) : lower quartile = lowest cut off (25%) of data = 25th percentile2β second quartile (Q2) : median = it cuts data set in half = 50th percentile3β third quartile (Q3) : upper quartile = highest cut off (25%) of data, or lowest 75% = 75th percentile4β fourth quartile (Q4) : maximal value
Example, bestie, an actual runnable one π :
my @data = (1..10);
my $stat = Statistics::Descriptive::Full->new();
$stat->add_data(@data);
print $stat->quantile(0); # => 1
print $stat->quantile(1); # => 3.25
print $stat->quantile(2); # => 5.5
print $stat->quantile(3); # => 7.75
print $stat->quantile(4); # => 10
$stat->median();β sorts the data and hands you back the median value. That's it. That's the whole vibe. β¨$stat->harmonic_mean();β returns the harmonic mean of the data. But β and this is the part where you pay attention π β the mean is undefined if any of the data are zero, or if the sum of the reciprocals is zero. In both of those cases you getundefback. Not an error, not a warning, justundef. Handle it.$stat->geometric_mean();β returns the geometric mean of the data. Clean, simple, iconic. πmy $mode = $stat->mode();β returns the mode of the data. The mode is the most commonly occurring datum. There's a whole Wikipedia page for it: <http://en.wikipedia.org/wiki/Mode_%28statistics%29> . If every value occurs only once, thenmode()will returnundefβ which lowkey makes sense because there genuinely is no mode, bestie. π$stat->sumsq()β the sum of squares. That's the entire description. It's giving minimalism. π¦$stat->trimmed_mean(ltrim[,utrim]);β okay sotrimmed_mean(ltrim)returns the mean with a fractionltrimof entries at each end dropped. Andtrimmed_mean(ltrim,utrim)returns the mean after a fractionltrimhas been removed from the lower end of the data and a fractionutrimhas been removed from the upper end. This method sorts the data before beginning to analyze it, so heads up on that. Also, all calls totrimmed_mean()are cached so they don't have to be calculated a second time. Slay. β$stat->frequency_distribution_ref($partitions);$stat->frequency_distribution_ref(\@bins);$stat->frequency_distribution_ref();β three ways to call, one method, we love a versatile icon π
So frequency_distribution_ref($partitions) slices the data into $partition sets (where $partition is greater than 1) and counts the number of items that fall into each partition. It returns a reference to a hash where the keys are the numerical values of the partitions used. Two rules that are lowkey important: the minimum value of the data set is not a key, and the maximum value of the data set is always a key. The number of entries for a particular partition key are the number of items which are greater than the previous partition key and less then or equal to the current partition key. As an example:
$stat->add_data(1,1.5,2,2.5,3,3.5,4);
$f = $stat->frequency_distribution_ref(2);
for (sort {$a <=> $b} keys %$f) {
print "key = $_, count = $f->{$_}\n";
}
prints
key = 2.5, count = 4
key = 4, count = 3
since there are four items less than or equal to 2.5, and 3 items greater than 2.5 and less than 4. Math! It's mathing! π§
frequency_distribution_refs(\@bins) provides the bins that are to be used for the distribution. This allows for non-uniform distributions as well as trimmed or sample distributions to be found. @bins must be monotonic and contain at least one element. Note that unless the set of bins contains the range, the total counts returned will be less than the sample size β so don't come for the module when your numbers look short, bestie, check your bins. π
Calling frequency_distribution_ref() with no arguments returns the last distribution calculated, if such exists.
my %hash = $stat->frequency_distribution($partitions);my %hash = $stat->frequency_distribution(\@bins);my %hash = $stat->frequency_distribution();β same asfrequency_distribution_ref()except that it returns the hash clobbered into the return list. Kept for compatibility reasons with previous versions ofStatistics::Descriptive, and using it is discouraged. It's giving legacy. It's giving "we keep it around but we don't endorse it." π$stat->least_squares_fit();$stat->least_squares_fit(@x);βleast_squares_fit()performs a least squares fit on the data, assuming a domain of@xor a default of1..$stat->count(). It returns an array of four elements($q, $m, $r, $rms)where:$q and $mβ satisfy the equationC($y = $m*$x + $q).$rβ is the Pearson linear correlation cofficient.$rmsβ is the root-mean-square error.
In case of error or division by zero, the empty list is returned. (Yes, the original says "If case". We keep it. We respect the lore. π«Ά)
The array that is returned can be "coerced" into a hash structure by doing the following:
my %hash = ();
@hash{'q', 'm', 'r', 'err'} = $stat->least_squares_fit();
Because calling least_squares_fit() with no arguments defaults to using the current range, there is no caching of the results. Every call, fresh math. π
πΈ REPORTING ERRORS πΈ
I read my email frequently, but since adopting this module I've added 2 children and 1 dog to my family, so please be patient about my response times. (Valid. Respect the chaos. πΆ) When reporting errors, please include the following to help me out:
- Your version of perl. This can be obtained by typing
perl "-v"at the command line. - Which version of
Statistics::Descriptiveyou're using. As you can see below, I do make mistakes. Unfortunately for me, right now there are thousands of CD's with the version of this module with the bugs in it. Fortunately for you, I'm a very patient module maintainer. πβ¨ - Details about what the error is. Try to narrow down the scope of the problem and send me code that I can run to verify and track it down.
π AUTHOR π
Current maintainer:
Shlomi Fish, <http://www.shlomifish.org/> , "shlomif@cpan.org"
Previously:
Colin Kuskie
My email address can be found at <http://www.perl.com> under Who's Who or at: <https://metacpan.org/author/COLINK> .
π«Ά CONTRIBUTORS π«Ά
Fabio Ponciroli & Adzuna Ltd. team (outliers handling) β absolute legends for this one, ngl.
π REFERENCES π
RFC2330, Framework for IP Performance Metrics- The Art of Computer Programming, Volume 2, Donald Knuth.
- Handbook of Mathematica Functions, Milton Abramowitz and Irene Stegun.
- Probability and Statistics for Engineering and the Sciences, Jay Devore.
π COPYRIGHT π
Copyright (c) 1997,1998 Colin Kuskie. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Copyright (c) 1998 Andrea Spinelli. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Copyright (c) 1994,1995 Jason Kastner. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
π LICENSE π
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
π SUPPORT π
Websites
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
- MetaCPAN β a modern, open-source CPAN search engine, useful to view POD in HTML format. <https://metacpan.org/release/Statistics-Descriptive>
- RT: CPAN's Bug Tracker β the RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN. <https://rt.cpan.org/Public/Dist/Display.html?Name=Statistics-Descriptive>
- CPANTS β the CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution. <http://cpants.cpanauthors.org/dist/Statistics-Descriptive>
- CPAN Testers β the CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions. <http://www.cpantesters.org/distro/S/Statistics-Descriptive>
- CPAN Testers Matrix β the CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms. <http://matrix.cpantesters.org/?dist=Statistics-Descriptive>
- CPAN Testers Dependencies β the CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution. <http://deps.cpantesters.org/?module=Statistics::Descriptive>
Bugs / Feature Requests
Please report any bugs or feature requests by email to "bug-statistics-descriptive at rt.cpan.org", or through the web interface at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Statistics-Descriptive>. You will be automatically notified of any progress on the request by the system. Spooky how it just knows. π
Source Code
The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)
<https://github.com/shlomif/perl-Statistics-Descriptive>
git clone git://github.com/shlomif/perl-Statistics-Descriptive.git
β AUTHOR β
Shlomi Fish <shlomif@cpan.org>
π BUGS π
Please report any bugs or feature requests on the bugtracker website <https://github.com/shlomif/perl-Statistics-Descriptive/issues>
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. Give us something we can actually run, bestie, we're begging π₯Ί
π¦ COPYRIGHT AND LICENSE π¦
This software is copyright (c) 1997 by Jason Kastner, Andrea Spinelli, Colin Kuskie, and others.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
And that's the whole page, no cap. β¨ This little masterpiece dropped from perl v5.42.0 on 2023-07-03, and it goes out to Statis...:Sparse(3pm) wherever they are. Go compute something cute. ππ
π¦ where this page comes from
- opensuse-leap 16.0: perl-Statistics-Descriptive 3.0801-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms