我需要检索data.frame
中子组的前%。关键是子组具有不同的长度,因此我无法选择任意等级来调整组子集的大小。我已经有一个正确排序的排名列。
vartype varname rank
a one 1
a two 2
b one 1
b two 2
b three 3
b four 4
c one 1
c two 2
c three 3
在上表中为每个 vartype 选择排名的前50%将返回:
vartype varname rank
a one 1
b one 1
b two 2
c one 1
c two 2
如果使用地板或天花板进行截止,这并不重要。谢谢!
答案 0 :(得分:8)
如果您不介意使用 dplyr :
dat <- read.table(text = "vartype varname rank
a one 1
a two 2
b one 1
b two 2
b three 3
b four 4
c one 1
c two 2
c three 3",header = TRUE,sep = "")
> dat %>% group_by(vartype) %>% filter(percent_rank(rank) <= 0.5)
Source: local data frame [5 x 3]
Groups: vartype
vartype varname rank
1 a one 1
2 b one 1
3 b two 2
4 c one 1
5 c two 2
答案 1 :(得分:6)
IIUC,你说你已经在rank
栏中订购了它们。然后,只需为每个组选择n
行中的N
行,n = ceiling(N/2)
。
假设dat
是您的data.frame,使用data.table
只是:
setDT(dat)[, .SD[seq_len(ceiling(.N/2))], by=vartype]
# vartype varname rank
# 1: a one 1
# 2: b one 1
# 3: b two 2
# 4: c one 1
# 5: c two 2
答案 2 :(得分:5)
这是一个使用基本功能的方法
dd[with(dd, ave(rank, vartype, FUN=function(x) x<=median(x)))==1, ]
我们使用ave
查看哪些排名大于每个组的中位数,然后我们选择这些排名的真实位置(==1
)。
答案 3 :(得分:3)
您可以使用data.table
来执行此操作
temp <- read.table(text =
"vartype varname rank
a one 1
a two 2
b three 1
b four 2
b one 3
b two 4
c one 1
c two 2
c three 3", header = T)
library(data.table)
setDT(temp)[, list(rank = rank[seq_len(ceiling(length(rank)/2))],
varname = varname[seq_len(ceiling(length(rank)/2))]), by = vartype]
# vartype rank varname
# 1: a 1 one
# 2: b 1 one
# 3: b 2 two
# 4: c 1 one
# 5: c 2 two