Created
April 12, 2021 10:09
-
-
Save ear7h/e30755ea405759c8a603b10f2683b747 to your computer and use it in GitHub Desktop.
simple stats function implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List | |
mean x = (sum x) / (fromIntegral $ length x) | |
med xs = med' $ sort xs | |
med' [x] = x | |
med' [x, y] = (x + y) / 2 | |
med' xs = med' $ drop 1 $ take (length xs - 1) xs | |
mode :: (RealFrac a) => [a] -> [(a, Int)] | |
mode xs = foldr f [] $ map mf groups | |
where | |
groups = group $ sort xs | |
mf :: [a] -> (a, Int) | |
mf = (\x -> (head x, length x)) | |
f :: Num a => (a, Int) -> [(a, Int)] -> [(a, Int)] | |
f (x, n) [] = [(x, n)] | |
f (x, n) acc @ ((xa, na):_) = | |
if n > na then [(x, n)] | |
else if n == na then (x, n):acc | |
else acc | |
range xs = (maximum xs) - (minimum xs) | |
iqr xs = (quartile 3 xs) - (quartile 1 xs) | |
quartile n = quartile' n . sort | |
quartile' :: (RealFrac a) => Int -> [a] -> a | |
quartile' 0 xs = minimum xs | |
quartile' 4 xs = maximum xs | |
quartile' n xs = | |
let | |
q = (fromIntegral n) / 4 * (fromIntegral $ 1 + length xs) - 1 | |
idx = (floor q) :: Int | |
off = (q - (fromIntegral idx)) | |
in ((1 - off) * (xs!!idx) + off * xs!!(idx + 1)) | |
variance :: RealFrac a => [a] -> a | |
variance xs = | |
let | |
m = mean xs | |
sq x = x * x | |
in (/ (fromIntegral $ length xs)) $ sum $ map (sq . (\x -> x - m)) xs | |
-- sample variance | |
varianceS:: RealFrac a => [a] -> a | |
varianceS xs = | |
let | |
m = mean xs | |
sq x = x * x | |
in (/ ((fromIntegral $ length xs) -1)) $ sum $ map (sq . (\x -> x - m)) xs | |
stddev = sqrt . variance | |
-- sample stddev | |
stddevS = sqrt . varianceS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment