gpt4 book ai didi

r - 按组计算最小值和最大值(范围)

转载 作者:行者123 更新时间:2023-12-01 14:30:30 25 4
gpt4 key购买 nike

我在数据框中有这样的东西:

PersonId Date_Withdrawal
A 2012-05-01
A 2012-06-01
B 2012-05-01
C 2012-05-01
A 2012-07-01
A 2012-10-01
B 2012-08-01
B 2012-12-01
C 2012-07-01
我想通过“PersonId”获取最小和最大日期

最佳答案

首先,转换为适当的日期类(始终是一个好习惯),然后您可以运行一个简单的 range按组。这是一个尝试

library(data.table)
setDT(df)[, Date_Withdrawal := as.IDate(Date_Withdrawal)]
df[, as.list(range(Date_Withdrawal)), by = PersonId]
# PersonId V1 V2
# 1: A 2012-05-01 2012-10-01
# 2: B 2012-05-01 2012-12-01
# 3: C 2012-05-01 2012-07-01

或者
library(dplyr)
df %>%
mutate(Date_Withdrawal = as.Date(Date_Withdrawal)) %>%
group_by(PersonId) %>%
summarise(Min = min(Date_Withdrawal), Max = max(Date_Withdrawal))
# Source: local data frame [3 x 3]
#
# PersonId Min Max
# (fctr) (date) (date)
# 1 A 2012-05-01 2012-10-01
# 2 B 2012-05-01 2012-12-01
# 3 C 2012-05-01 2012-07-01

附言底座 aggregate看起来像 aggregate(as.Date(Date_Withdrawal) ~ PersonId, df, range)但它拒绝保留类。

关于r - 按组计算最小值和最大值(范围),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33090847/

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