[R] Creating a histogram from a frequency vector

Stephen Ellison S@E|||@on @end|ng |rom LGCGroup@com
Wed Oct 9 18:29:28 CEST 2019


> I have a vector like say 73,53,42,67,41,50 where these numbers are the
> number of occurrences of the data values 1,2,3,4,5,6 - so in essence I have
> the frequency bit from the hist() function.  I can't see an elegant way (there
> are clearly messy workarounds like generating a vector of 73 1's, 53 2's etc) of
> creating a histogram from this data set.  Is there one?

hist() generates a histogram object that it then plots.

You can use your frequency vector to generate the same kind of object and then just plot it, though you'll have to provide breaks (possibly defaulted, if they're just 0:length(frequencies) ) and you'd have to work on the density component a bit.

I'm sure this is out there somewhere already, but here's as an example, using values pulled from a (nonequidistant) ?hist example and using a short off-the-cuff function to build the histogram object:

freqs <- c(11, 19,  5,  3,  2,  1,  0,  0,  2,  3,  2) #islands
brks <- c(4*0:5, 10*3:5, 70, 100, 140)

freqhist <- function(counts, xname=deparse(substitute(frequencies)), breaks=0:length(frequencies), 
	mids=(breaks[-1]+breaks[-length(breaks)])/2 , ...){
	
	binwidths <- diff(breaks) #This copes with unequal break intervals
	dens <- counts/(binwidths*sum(counts))

	retval <- structure(list(breaks=breaks, counts=counts,, density=dens, mids=mids, xname=xname, equidist=all(diff(breaks)==diff(breaks[1:2]) ),
		class="histogram")
}

plot(freqhist(freqs, breaks=brks))

#Also works equidistant with default 0:length(counts) breaks:

f2 <- c(30, 39, 31, 29, 10,  6,  3,  1,  0,  1)
plot(freqhist(f2))

Steve Ellison





*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list