我有一个数据框:
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))
我希望为var
的每个值获取index
的所有最小值S及其关联的P
。
我可以这样做:
DT <- data.table(df)
DT[ ,.SD[which.min(var)], by = P]
,var
只提供P
(第一个)的最小值:
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
想法?
答案 0 :(得分: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
答案 1 :(得分: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