R 子集 data.frame 从一个向量的最大值并按另一个分组 [英] R Subset data.frame from max value of one vector and grouped by another
问题描述
>ID<-c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C')
>WK<-c(1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5)
>NumSuccess<-c(0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 3)
>Data<-data.frame(ID, WK, NumSuccess)
我正在尝试根据NumSuccesses"中的值创建一个子集 data.frameData2",该值对应于按ID"分组的WK"中的最大值.生成的 data.frame 应如下所示:
I am trying to create a subset data.frame "Data2" based on the value in "NumSuccesses" that corresponds to the Max Value in "WK" grouped by "ID". Resulting data.frame should look like this:
>ID<-c('A','B','C')
>WK<-c(3, 3, 5)
>NumSuccess<-c(2, 1, 3)
>Data2<-data.frame(ID, WK, NumSuccess)
推荐答案
这可以通过多种方式完成.如果WK"有关系,每个ID"的最大值并希望所有行都具有最大WK",则使用逻辑条件(WK==max(WK)
) 按ID"分组后.
This could be done in more than one way. If there are ties for 'WK', maximum value per each 'ID' and want all the rows with the maximum 'WK', it may be useful to filter
with the logical condition (WK==max(WK)
) after grouping by the 'ID'.
library(dplyr)
Data %>%
group_by(ID) %>%
filter(WK==max(WK))
# ID WK NumSuccess
#1 A 3 2
#2 B 3 1
#3 C 5 3
如果每个 'ID' 的 'WK' 有一个 'max' 值,我们可以使用 which.max
或使用 arrange
按'对数据集进行排序每个'ID'的WK'
If there is a single 'max' value for 'WK' per 'ID', we can use which.max
or use arrange
to order the dataset by 'WK' for each 'ID'
Data %>%
group_by(ID) %>%
slice(which.max(WK))
# ID WK NumSuccess
#1 A 3 2
#2 B 3 1
#3 C 5 3
Data %>%
group_by(ID) %>%
arrange(-WK) %>%
slice(1)
data.table
中的类似方法是
library(data.table)
setDT(Data)[, .SD[max(WK)==WK], ID]
setDT(Data)[, .SD[which.max(WK)], ID]
setkey(setDT(Data), WK)[, .SD[.N], ID]
或者我们可以使用 base R
中的 ave
Or we can use ave
from base R
Data[with(Data, ave(WK, ID, FUN=max)==WK),]
这篇关于R 子集 data.frame 从一个向量的最大值并按另一个分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!