我试图通过ID来说明在条形图中连续应用各种(限制性越来越小的)样本限制的样本大小的效果,如下所示:
蓝色条是在完成所有5个限制之后剩下的;金条显示限制条件最少的影响;春天绿色条显示第二个最小限制条件的影响;等等。
以下是一些示例数据:
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)
我到目前为止使用的代码还有一些不足之处 - 1)它相当冗长; 2)它不会让我觉得非常强大/可推广。有没有人有一些经验可以产生这样的东西,可以在这两个方面提供一些改进?我觉得这种类型的图表在数据分析中应该很常见,所以我很惊讶它没有特殊功能。
这是我到目前为止所做的事情:
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)}]
不漂亮。感谢您的投入。
答案 0 :(得分:2)
正如@Frank所指出的,如果将所有这些连续的标志转换为分类变量,例如,蓝色条形图为1,金条条形图为2,弹簧条形条形图为3,等等,则更简单
正如@Frank所指出的那样,max.col
为我们提供了一种方便的方法来创建一个完全取得这些值的变量,并且很快:
dt[,categ2:=max.col(cbind(.5,.SD),ties.method="last"),
.SDcols=paste0("flag",5:1)]
(这里发生了什么?max.col
正在为我们分配最右边的标志的递归性质 - 因为每列中的ties.method="last"
- TRUE
值;如果所有标志都是FALSE
,第一列是最大的,因为它总是.5,大于0.查看此表:)
0 1 2 3 4 5
.5 F F F F F # No flags apply, so column 0 wins
.5 T F T F F # Flags 1 & 3 true--3 is the binding condition--
# Once Flag 5 is applied, it no longer matters
# which of the subsequent flags may or may not apply.
如此定义categ
,图形变得简单:
dt[,barplot(table(categ,id))]
会工作吗?得到所有的花里胡哨:
dt[,barplot(table(categ,id)[,5:1],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)]