Last active
November 20, 2020 11:03
-
-
Save k-barton/4ab58302080b1e4c4d919259b4fdd3a7 to your computer and use it in GitHub Desktop.
Compute/plot a weighted histogram using base graphics.
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
weighted.histogram <- | |
function() { | |
cl <- match.call() | |
cl$w <- NULL | |
cl[[1L]] <- as.name("hist.default") | |
cl$plot <- FALSE | |
h <- eval.parent(cl) | |
f <- factor(findInterval(x, h$breaks, left.open = TRUE, | |
rightmost.closed = TRUE, | |
all.inside = TRUE), | |
levels = seq.int(length(h$breaks) - 1L)) | |
y <- tapply(w, f, sum, na.rm = TRUE) | |
y[is.na(y)] <- 0 | |
h$counts <- y * length(f) | |
h$density <- y / diff(h$breaks) | |
if (plot) { | |
if (is.null(freq)) | |
freq <- if (!missing(probability)) | |
!as.logical(probability) else h$equidist | |
breaks <- h$breaks | |
xname <- h$xname | |
plot(h, freq = freq, col = col, border = border, angle = angle, | |
density = density, main = main, xlim = xlim, ylim = ylim, | |
xlab = xlab, ylab = ylab, axes = axes, labels = labels, | |
...) | |
invisible(h) | |
} else h | |
} | |
formals(weighted.histogram) <- | |
append(formals(hist.default), alist(w = ), after = 1) | |
formals(weighted.histogram)['main'] <- alist(paste("Weighted histogram of", xname)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This function modifies
hist.default
by adding a weights argument (w
, 2-nd position). The usage is as inhist.default
.