I'm trying to illustrate the effects, by ID, on sample size of successively applying various (decreasingly restrictive) sample restrictions in a bar plot that looks something like this:
The blue bar is what remains after all 5 restrictions are placed; the gold bar shows the impact of the least restrictive condition; the spring green bar shows the impact of the second-least restrictive condition; and so forth.
Here's some sample data:
library(data.table)
set.seed(8195)
dt<-data.table(id=rep(1:5,each=2e3),flag1=!!runif(1e4)>.76,
flag2=!!runif(1e4)>.88,flag3=!!runif(1e4)>.90,
flag4=!!runif(1e4)>.95,flag5=!!runif(1e4)>.99)
The code I'm using so far leaves something to be desired-- 1) it's rather verbose and 2) it doesn't strike me as very robust/generalizable. Does anyone have some experience producing something like this that can offer some improvements on either of these fronts? I have a feeling this type of graph should be pretty common in data analysis, so I'm sort of surprised there's not a special function for it.
Here's what I'm doing so far:
dt[order(-id)][,
#to find out how many observations are lost by
# applying flag 1 (we keep un-flagged obs.),
# look at the count of indices before and
# after applying flag 1
{l1<-!flag1;i1<-.I[l1];n1<-length(.I)-length(i1);
#to find the impact of flag 2, we apply flag 2
# _in addition to_ flag 1--the observations
# we keep have _neither_ flag 1 _nor_ flag 2;
# the impact is measured by the number of
# observations lost by applying this flag
# (that weren't already lost from flag 1)
l2<-l1&!flag2;i2<-.I[l2];n2<-length(i1)-length(i2);
l3<-l2&!flag3;i3<-.I[l3];n3<-length(i2)-length(i3);
l4<-l3&!flag4;i4<-.I[l4];n4<-length(i3)-length(i4);
l5<-l4&!flag5;i5<-.I[l5];n5<-length(i4)-length(i5);
#finally, the observations we keep have _none_
# of flags 1-5 applied
n6<-length(i5);
c(n6,n5,n4,n3,n2,n1)},by=id
][,{barplot(matrix(V1,ncol=uniqueN(id)),
horiz=T,col=c("blue","gold","springgreen",
"orange","orchid","red"),
names.arg=paste("ID: ",uniqueN(id):1),
las=1,main=paste0("Impact of Sample Restrictions",
"\nBy ID"),
xlab="Count",plot=T)}]
Not pretty. Thanks for your input.