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

3

我有一个数据框:

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
有什么想法吗?

据我理解,您想要每个唯一的索引和P配对的最小值...然而,您所期望的输出中,为什么P == 'A'有两个观测值?同时,按照同样的规则,您只有P值为'B'和'C'的唯一观测值。 - Steven_
1
这应该会有所帮助:https://dev59.com/7W015IYBdhLWcg3w9wl1 - TBSRounder
2个回答

5
使用 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

4

which.min的帮助页面上可以看到以下内容:

确定数字(或逻辑)向量的最小值或最大值的位置,即索引。

如果您想要找到与最小值相匹配的所有值,您应该尝试使用==。因此,继续您的方法,请尝试:

DT[, .SD[var == min(var)], by = P]
##    P index var
## 1: A  ind2   1
## 2: A  ind3   1
## 3: B  ind3   4
## 4: C  ind1   2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接