Very many thanks to Tim Hesterberg of Insightful, whose "quick and dirty"
hint (his description) inspired me to tackle my very first S-Plus
programming project.
The following code is the result:
w8d.density <- function(x, w8s, lo=-0.2, hi=1.0, bin=0.01){
#defines the function
#compulsory arguments name
#data: x
#weighting data: w8s
#optional arguments name default
#lower boundary of histogram: lo -0.2
#upper boundary: hi 1.0
#bin width: bin 0.01
a <- seq(lo, (hi-bin), bin)
b <- seq((lo+bin), hi, bin)
#creates vectors of bin upper and lower boundaries
density <- c(1:length(a))
#creates vector of bin contents
for(i in 1:length(a)) {
density[i] <- sum( w8s[a[i] < x & x <= b[i] ] ) / sum(w8s)
}
#weights data in bins
#note that densities are relative to the whole of x, not just the segment
being charted
names <- paste(a)
#creates labels for bins
barplot(density, names=names, space=0, inside=F, blocks=F, axes=T,
sbdensity=0)
#plots density histogram
}
Some obvious improvements would name the bars after the midpoints, not the
lower boundaries, and (given my default arguments) omit most of the names so
that the remainder can actually be read...
Julian Wells
OU Business School
The Open University
Walton Hall
Milton Keynes
MK7 6AA
United Kingdom
+44 1908 654658
|