Sunday, October 2, 2016

Finding the mode of a data set with PowerShell

PowerShell's Measure-Object (or just measure) cmdlet can get the mean of a list of numbers if you pass the -Average flag. There doesn't appear to be a built-in way to get the mode (most common value), though. Fortunately, it's possible to use a bit of piping to do the job:

$myList | group | sort -Property Count -Descending

The results will be a list of the different values and their frequencies, with the most common ones at the top. To just get the mode for use in further calculations, get the first group from the list of groups and then take an element from the list of its contents (which should all be the same for plain numbers):

($myList | group | sort -Property Count -Descending)[0].Group[0]

No comments:

Post a Comment