gpt4 book ai didi

r - 如何按组获取变量的所有最小值?

转载 作者:行者123 更新时间:2023-12-04 09:47:14 24 4
gpt4 key购买 nike

我有一个数据框:

df<-data.frame(P = c("A","A","A", "B","B","B", "C", "C", "C"), 
index = c("ind1","ind2","ind3","ind1","ind2","ind3","ind1","ind2","ind3"),
var = c(2,1,1,8,5,4,2,8,6))

我想为 P 的每个值获取 var 的所有最小值及其关联的 index。我可以这样做:

DT <- data.table(df)
DT[ ,.SD[which.min(var)], by = P]

P 仅给出 var 的一个最小值(第一个):

   P index  var
1: A ind2 1
2: B ind3 4
3: C ind1 2

我想:

   P index  var
1: A ind2 1
2: A ind3 1
2: B ind3 4
3: C ind1 2

想法?

最佳答案

使用 dplyr,您可以使用以下方法之一:

library(dplyr)
DT %>% group_by(P) %>% filter(var == min(var)) # or %in% instead of ==
#Source: local data table [4 x 3]
#Groups: P
#
# P index var
# (fctr) (fctr) (dbl)
#1 A ind2 1
#2 A ind3 1
#3 B ind3 4
#4 C ind1 2

或者

DT %>% group_by(P) %>% top_n(1, desc(var)) # top_n() returns multiple rows in case of ties
#Source: local data table [4 x 3]
#Groups: P
#
# P index var
# (fctr) (fctr) (dbl)
#1 A ind2 1
#2 A ind3 1
#3 B ind3 4
#4 C ind1 2

或者

DT %>% group_by(P) %>% filter(min_rank(var) == 1)
#Source: local data table [4 x 3]
#Groups: P
#
# P index var
# (fctr) (fctr) (dbl)
#1 A ind2 1
#2 A ind3 1
#3 B ind3 4
#4 C ind1 2

关于r - 如何按组获取变量的所有最小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34438938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com