Skip to content

Commit

Permalink
mad
Browse files Browse the repository at this point in the history
  • Loading branch information
shanedrabing committed Jul 26, 2021
1 parent e5b714d commit c9eb4cb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
15 changes: 13 additions & 2 deletions pyrat/stats.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
__all__ = [
"sd",
"cor",
"cov",
"dev",
"mad",
"median",
"na_omit",
"sd",
"ss",
"var",
"cor"
]


Expand Down Expand Up @@ -110,3 +111,13 @@ def cor(x, y, na_rm=False):
elif any(is_na(x)) or any(is_na(y)):
return NA
return cov(x, y) / (sd(x) * sd(y))


def mad(x, f=median, constant=1.4826, na_rm=False):
if not isvector(x):
x = c(x)
if na_rm:
x = na_omit(x)
elif any(is_na(x)):
return NA
return constant * f(abs(dev(x, f=f, na_rm=na_rm)))
9 changes: 9 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,3 +433,12 @@ def none(x):
assert_eq(cor(v123, v213), 0.5)
assert_eq(cor(v123, c(1, 2, 3, NA)), NA)
assert_eq(cor(v123, c(1, 2, 3, NA), na_rm=True), 1)

# mad, mean absolute deviation
assert_error(mad, TypeError)
assert_eq(mad(0), 0)
assert_eq(mad(NA), NA)
assert_eq(mad(v123), 1.4826)
assert_eq(mad(v123, constant=1), 1)
assert_eq(mad(c(NA, v123)), NA)
assert_eq(mad(c(NA, v123), na_rm=True), 1.4826)

0 comments on commit c9eb4cb

Please sign in to comment.