通常,我想获得一列分布的数据框架的顶部五分之一。但是,对于另一列的每个独特的分类价值,它都必须是顶级五分之一。
我想必须以几个步骤完成,并有可能使用循环进行。首先,我需要根据唯一的分类值将数据帧分开,然后仅保留每个新数据框架的顶部五分位数,然后再将数据框架再次划分。但是我不知道该怎么做。
一些示例数据:
dat <- data.frame(x = rep(letters[1:3],times = 5),
y = rep(1:3,each = 5))
> dat
x y
1 a 1
2 b 1
3 c 1
4 a 1
5 b 1
6 c 2
7 a 2
8 b 2
9 c 2
10 a 2
11 b 3
12 c 3
13 a 3
14 b 3
15 c 3
在步骤1中,我想为每个唯一的分类值创建一个数据框。类似:
> df.a
x y
1 a 1
2 a 1
3 a 2
4 a 2
5 a 3
DF.B和DF.C相应地
在第二步中,我只想保留每个新数据框架的顶部五分之一。类似:
应该成为这个:
> df.a=df.a[df.a$y > quantile(df.a, 0.5, na.rm = TRUE),]
# taking the top 50% because the top quintile would not work with the sample data.
在最后一步中,我需要重新安排所有新的数据帧。
正如您所指出的,您的示例数据很难使用五分之一,因此我会稍微更改您的示例数据。
## New data
dat <- data.frame(x = rep(letters[1:3],times = 25),
y = sample(10, 75, replace=TRUE))
为了获取五分位数,无需为分类变量的每个值进行单独的数据。您可以使用aggregate
做到这一点。
Limits = aggregate(dat$y, list(dat$x), quantile, 0.8)
row.names(Limits) = Limits[,1]
(Limits = Limits [,-1, drop=FALSE])
x
a 8.0
b 7.2
c 8.0
现在,将(Top(五分位数的表划分为类别,我们可以选择以上五分位数(按类别(上方的原始数据的一部分。
TopQuintile = dat[which(dat$y >= Limits[dat$x,1]), ]