From 62fcb55b783e297596dc50303653b90fd58a24df Mon Sep 17 00:00:00 2001 From: Stanislaw Swierc Date: Tue, 2 Jan 2018 06:28:52 -0800 Subject: [PATCH] ap@k in R should work even if one of the vectors is empty --- R/R/metrics.r | 5 +++++ R/inst/tests/test-apk.r | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/R/R/metrics.r b/R/R/metrics.r index 3d8ad57..6dcc03e 100644 --- a/R/R/metrics.r +++ b/R/R/metrics.r @@ -164,6 +164,11 @@ logLoss <- function(actual, predicted) mean(ll(actual, predicted)) #' @export apk <- function(k, actual, predicted) { + if (length(actual) == 0 || length(predicted) == 0) + { + return(0.0) + } + score <- 0.0 cnt <- 0.0 for (i in 1:min(k,length(predicted))) diff --git a/R/inst/tests/test-apk.r b/R/inst/tests/test-apk.r index e7b4985..ace9c68 100644 --- a/R/inst/tests/test-apk.r +++ b/R/inst/tests/test-apk.r @@ -6,6 +6,9 @@ test.apk <- function() checkEqualsNumeric(apk(3, c(1,3), 1:5), 5/6) checkEqualsNumeric(apk(3, 1:3, c(1,1,1)), 1/3) checkEqualsNumeric(apk(3, 1:3, c(1,2,1)), 2/3) + checkEqualsNumeric(apk(3, 1:3, numeric(0)), 0.0) + checkEqualsNumeric(apk(3, numeric(0), 1:3), 0.0) + checkEqualsNumeric(apk(3, numeric(0), numeric(0)), 0.0) } test.mapk <- function() @@ -15,5 +18,5 @@ test.mapk <- function() checkEqualsNumeric(mapk(3, list(c(1,3,4),c(1,2,4),c(1,3)), list(1:5,1:5,1:5)), 0.685185185185185) checkEqualsNumeric(mapk(5, list(1:5,1:5), list(c(6,4,7,1,2),c(1,1,1,1,1))), 0.26) checkEqualsNumeric(mapk(3, list(c(1,3),1:3,1:3), list(1:5,c(1,1,1),c(1,2,1))), 11/18) - + checkEqualsNumeric(mapk(3, list(), list()), 0.0) } \ No newline at end of file