XML technologies / XSLT / XSLT Cookbook / Numbers and calculations / Computing statistical functions
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
You need to calculate averages, variances and standard deviations.
Solution
XSLT 1.0
Statisticians use three kinds of average: mean, median and mode.
The mean is trivial: sum using recipe Calculate sums and products, then divide by the number of values summed.
The median is the middle number in a sorted set. If the number of values is even, generally take the mean of the two middle numbers:
<xsl:template name="ckbk:median">
<xsl:param name="nodes" select="/.."/>
<xsl:variable name="count" select="count($nodes)"/>
<xsl:variable name="middle" select="ceiling($count div 2)"/>
<xsl:variable name="even" select="not($count mod 2)"/>
<xsl:variable name="m1">
<xsl:for-each select="$nodes">
<xsl:sort data-type="number"/>
<xsl:if test="position( ) = $middle">
<xsl:value-of select=". + ($even * ./following-sibling::*[1])"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
<!-- Der Median -->
<xsl:value-of select="$m1 div ($even + 1)"/>
</xsl:template>The even case uses the Boolean-to-number conversion trick seen elsewhere in the book. For an odd node count, $m1 selects exactly the middle node, and dividing by 1 gives the answer. For an even count, $m1 is the sum of the two middle nodes, so divide by 2.
The mode is the most frequent item or items in a set, which need not be numeric. If identical nodes also have identical string values, use this solution:
<xsl:template name="ckbk:mode">
<xsl:param name="nodes" select="/.."/>
<xsl:param name="max" select="0"/>
<xsl:param name="mode" select="/.."/>
<xsl:choose>
<xsl:when test="not($nodes)">
<xsl:copy-of select="$mode"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="first" select="$nodes[1]"/>
<xsl:variable name="try" select="$nodes[. = $first]"/>
<xsl:variable name="count" select="count($try)"/>
<!-- Rekursion mit Knoten, die nicht gleich dem ersten Knoten sind -->
<xsl:call-template name="ckbk:mode">
<xsl:with-param name="nodes" select="$nodes[not(. = $first)]"/>
<!-- Wenn wir einen Knoten gefunden haben, der häufiger auftritt, dann wird der Zähler count übergeben, ansonsten wird der alte max count übergeben -->
<xsl:with-param name="max" select="($count > $max) * $count + not($count > $max) * $max"/>
<!-- Berechnen des neuen Modus als ... -->
<xsl:with-param name="mode">
<xsl:choose>
<!-- das erste Element in try, falls wir einen neuen max-Wert gefunden haben -->
<xsl:when test="$count > $max">
<xsl:copy-of select="$try[1]"/>
</xsl:when>
<!-- der alte Modus vereinigt mit dem ersten Element in try, falls wir einen äquivalenten count-Wert zum aktuellen max-Wert gefunden haben -->
<xsl:when test="$count = $max">
<!-- Achtung: Sie müssen $mode in eine Knotenmenge konvertieren, wenn Sie eine Version von XSLT benutzen, die keine automatische Konvertierung vornimmt -->
<xsl:copy-of select="$mode | $try[1]"/>
</xsl:when>
<!-- ansonsten bleibt der alte Modus gleich -->
<xsl:otherwise>
<xsl:copy-of select="$mode"/>
</xsl:otherwise>
</xsl:choose>
</xsl:with-param>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>Otherwise, replace the comparisons with an appropriate test. For example, if equality depends on an attribute named age, the test is ./@age = $first/@age.
Variance and standard deviation describe the distribution or spread of values around the mean. The simplest variance calculation obtains three quantities: sum = the sum of the numbers, sum-sq = the sum of their squares, and count = the number of values. The variance is then (sum-sq – sum2 / count) / count – 1. The following tail-recursive template computes all three in one pass:
<xsl:template name="ckbk:variance">
<xsl:param name="nodes" select="/.."/>
<xsl:param name="sum" select="0"/>
<xsl:param name="sum-sq" select="0"/>
<xsl:param name="count" select="0"/>
<xsl:choose>
<xsl:when test="not($nodes)">
<xsl:value-of select="($sum-sq - ($sum * $sum) div $count) div ($count - 1)"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="value" select="$nodes[1]"/>
<xsl:call-template name="ckbk:variance">
<xsl:with-param name="nodes" select="$nodes[position( ) != 1]"/>
<xsl:with-param name="sum" select="$sum + $value"/>
<xsl:with-param name="sum-sq" select="$sum-sq + ($value * $value)"/>
<xsl:with-param name="count" select="$count + 1"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>You may recognize this template as a variant of ckbk:sum , extended to compute the other two variance components. Without tail-recursion support, large sets cause problems. Use an alternative, piecewise strategy based on the standard variance definition: ∑ ⟦U+0001⟧(Mittelwert – xi)2 / (Zähler – 1). First compute the mean with the divide-and-conquer or batch form of summation, divided by the count. Then use a divide-and-conquer or batch template to sum the squared differences between the mean and each value. Finally divide by Zähler – 1.
Once variance is available, standard deviation is its square root; see recipe Implementing common mathematical functions for square-root calculation.
XSLT 2.0
<!-- Median -->
<xsl:function name="ckbk:median">
<xsl:param name="nodes" as="xs:double*" />
<xsl:variable name="count" select="count($nodes)"/>
<xsl:variable name="middle" select="ceiling($count div 2)"/>
<xsl:variable name="sorted" as="xs:double*">
<xsl:perform-sort select="$nodes">
<xsl:sort data-type="number"/>
</xsl:perform-sort>
</xsl:variable>
</xsl:function>
<!-- Modus -->
<xsl:function name="ckbk:mode" as="item( )*">
<xsl:param name="nodes" as="item( )*"/>
<!-- Zuerst werden die einzelnen Werte gesucht -->
<xsl:variable name="distinct" select="distinct-values($nodes)" as="item( )*"/>
<!--Erstellen einer Sequenz der Häufigkeitszähler der einzelnen Werte -->
<xsl:variable name="counts" select="for $i in $distinct return count($nodes[. = $i])" as="xs:integer*"/>
<!--Maximalwert der Zähler ermitteln -->
<xsl:variable name="max" select="max($counts)" as="xs:integer?"/>
<!-- Rückgabe derjenigen Werte, die den maximalen Zähler aufweisen -->
<xsl:sequence select="$distinct[position( ) = index-of($counts,$max)]"/>
</xsl:function>
<!-- Varianz -->
<xsl:function name="ckbk:variance" as="xs:double">
<xsl:param name="nodes" as="xs:double*"/>
<xsl:variable name="sum" select="sum($nodes)"/>
<xsl:variable name="count" select="count($nodes)"/>
<xsl:sequence select="if ($count lt 2) then 0 else sum(for $i in $nodes return $i * $i) - $sum * $sum) div($count * $count - $count)"/>
</xsl:function>Discussion
XSLT 1.0
Statistical functions are common tools for numeric analysis, so these templates can complement your toolkit. XSLT, however, was not intended for statistics. Alternatively, use it as a front end to convert XML into comma- or tab-separated data, then import the data into a spreadsheet or statistics program.
XSLT 2.0
Again, the 2.0 solutions are much simpler. More revealingly, the 2.0 mode implementation was easier to derive, code and revise than 1.0. For the first edition, I spent several hours developing the 1.0 solution, then another hour debugging it. The 2.0 counterpart took about 15 minutes once I saw how to exploit function distinct-values.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de