gpt4 book ai didi

r - 按每组中的最大值过滤数据框

转载 作者:行者123 更新时间:2023-12-03 21:15:37 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Select the row with the maximum value in each group

(17 个回答)


4年前关闭。




我有一个 180,000 x 400 的数据框,其中的行对应于用户,但每个用户只有两行。

id   date  ...
1 2012 ...
3 2010 ...
2 2013 ...
2 2014 ...
1 2011 ...
3 2014 ...

我想对数据进行子集化,以便只保留每个用户的最新行(即每个 id 的日期值最高的行)。

我第一次尝试使用 which()循环 idsifelse()声明于 sapply()这是非常缓慢的( O(n^2) 我相信)。

然后我尝试对 df 进行排序来自 id然后以两个为增量循环并比较相邻的日期,但这也很慢(我猜是因为 R 中的循环是无望的)。两个日期的比较是瓶颈,因为排序几乎是即时的。

有没有办法对比较进行矢量化?

来自 Remove duplicates keeping entry with largest absolute value 的解决方案
aa <- df[order(df$id, -df$date), ] #sort by id and reverse of date
aa[!duplicated(aa$id),]

运行速度非常快!!

最佳答案

这是使用 data.table 包的简单快捷的方法

library(data.table)
setDT(df)[, .SD[which.max(date)], id]
# id date
# 1: 1 2012
# 2: 3 2014
# 3: 2 2014

或者(可能会快一点,因为键控 by
setkey(setDT(df), id)[, .SD[which.max(date)], id]

或者通过 data.table 使用 OPs 的想法包裹
unique(setorder(setDT(df), id, -date), by = "id")

或者
setorder(setDT(df), id, -date)[!duplicated(id)]

或基础 R 解决方案
with(df, tapply(date, id, function(x) x[which.max(x)]))
## 1 2 3
## 2012 2014 2014

其它的办法
library(dplyr)
df %>%
group_by(id) %>%
filter(date == max(date)) # Will keep all existing columns but allow multiple rows in case of ties
# Source: local data table [3 x 2]
# Groups: id
#
# id date
# 1 1 2012
# 2 2 2014
# 3 3 2014

或者
df %>%
group_by(id) %>%
slice(which.max(date)) # Will keep all columns but won't return multiple rows in case of ties

或者
df %>%
group_by(id) %>%
summarise(max(date)) # Will remove all other columns and wont return multiple rows in case of ties

关于r - 按每组中的最大值过滤数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27534284/

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