我有data.table
看起来像这样
test <- data.table(variable=c(rep(1:5,100)),percent=abs(rnorm(500,0,1)),select=c(501:1000))
我想做的是:每variable
,%>%
创建5%的间隔(例如[0,0.05),[0.05,0.1],[0.1,0.15),所以最后我会有20*5
个时间间隔,然后在这些时间间隔内挑选顶部(x)select
。
更新
> test[,cut(percent,20),by="variable"]
variable V1
1: 1 (0.726,0.841]
2: 1 (0.496,0.611]
3: 1 (0.266,0.381]
cut
无法按照我想要的方式运作,因为我没有得到所需的时间间隔
答案 0 :(得分:0)
这是我的解决方案。
breaks <- seq(0, 1, by=0.05) # this works better than length.out=20, because you
# avoid round errors
test[,interval:=cut(percent,breaks=breaks),by="variable"]
setkey(test,variable,percent)
test2 <- test[,tail(.SD,20),by=.(variable,interval)]