This question already has answers here:
Choose groups to keep/drop in data.table

(3个答案)



Subset rows corresponding to max value by group using data.table

(1个答案)


1年前关闭。




如果该组中的最大值大于某个值,我将尝试过滤data.table中该组中的所有行。以下是我如何在DPLY中进行操作以及如何在data.table中的两个步骤中使它工作。
#DPLYR
df<-data.table(
  x =1:12
  ,y = 1:3
)

df %>% group_by(y) %>%
  filter(max(x) < 11)

##data.table
df[,max_value :=max(x),by=y][max_value<11]

The output should be

    x y
1:  1 1
2:  4 1
3:  7 1
4: 10 1

有没有一种方法可以一步完成而不在我的数据集中创建列?我所能找到的只是对一个组进行子集化以获得一个组中的一个特定值,而不是返回该组中符合条件的所有行。

最佳答案

我们可以使用.I来获取行索引,提取索引列和子集

df[df[, .I[max(x) < 11], y]$V1]
#    x y
#1:  1 1
#2:  4 1
#3:  7 1
#4: 10 1

或另一种选择是.SD
df[, .SD[max(x) < 11], y]

关于r - 如果最大组值>某个值,则过滤data.table组内的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57698089/

10-12 17:31
查看更多