Skip to content

Commit

Permalink
fix density computation for discrete variables (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
tnagler committed May 6, 2018
1 parent 5ed40a3 commit 6de6901
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 2 additions & 2 deletions R/kde1d_methods.R
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ dkde1d <- function(x, obj) {
if (length(obj$jitter_info$i_disc) == 1 & !is.ordered(x))
x <- ordered(x, obj$jitter_info$levels$x)

fhat <- dkde1d_cpp(x, obj)
fhat <- dkde1d_cpp(expand_as_numeric(x), obj)

if (length(obj$jitter_info$i_disc) == 1) {
# for discrete variables we can normalize
f_all <- dkde1d_cpp(as.ordered(obj$jitter_info$levels$x), obj)
f_all <- dkde1d_cpp(seq_along(obj$jitter_info$levels$x) - 1, obj)
fhat <- fhat / sum(f_all)
}

Expand Down
6 changes: 6 additions & 0 deletions tests/testthat/test_kde1d.R
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,10 @@ test_that("behavior for discrete data is consistent", {
expect_true(all(is.na(dkde1d(c(0, 6), fit))))
expect_true(all(is.na(pkde1d(c(0, 6), fit))))
expect_true(all(rkde1d(n, fit) %in% x))
})

test_that("estimates for discrete data are reasonable", {
x <- ordered(sample(5, 1e5, TRUE), 1:5)
fit <- kde1d(x)
expect_true(all(abs(dkde1d(1:5, fit) - 0.2) < 0.1))
})

0 comments on commit 6de6901

Please sign in to comment.