我有一个数据框架:
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))我想得到所有的最小valueS of var及其关联的P值的index。我可以这么做:
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
想法?
发布于 2015-12-23 15:38:05
在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发布于 2015-12-23 15:42:57
使用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 2https://stackoverflow.com/questions/34438938
复制相似问题