Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按组计算最小值和最大值(范围)_R_Range_Aggregate - Fatal编程技术网

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

R 按组计算最小值和最大值(范围),r,range,aggregate,R,Range,Aggregate,我在数据框中有类似的内容: 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

我在数据框中有类似的内容:

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”获取最小和最大日期,然后转换为适当的日期类(始终是一个良好的做法),然后您可以按组运行一个简单的
范围。这是一个尝试

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


p.S.base
aggregate
看起来像
aggregate(as.Date(Date\u detaction)~PersonId,df,range)
但它拒绝保留类

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