>我有一组以下形式的Payment Date
:
ID Payment Date
1 18-01-01
1 18-02-03
2 18-04-03
2 18-05-08
2 18-06-06
3 17-12-23
3 18-01-22
3 18-02-24
4 17-11-09
4 18-12-06
我想添加一列,Activation Date
,作为每个ID
的最早付款日期,例如:
ID Payment Date Activation Date
1 18-01-01 18-01-01
1 18-02-03 18-01-01
2 18-04-03 18-04-03
2 18-05-08 18-04-03
2 18-06-06 18-04-03
3 17-12-23 17-12-23
3 18-01-22 17-12-23
3 18-02-24 17-12-23
4 17-11-09 17-11-09
4 18-12-06 17-11-09
我想知道与其进入循环并逐个处理每个 ID,不如有一种更聪明的方法可以做到这一点。
df = read.table(text = "
ID PaymentDate
1 18-01-01
1 18-02-03
2 18-04-03
2 18-05-08
2 18-06-06
3 17-12-23
3 18-01-22
3 18-02-24
4 17-11-09
4 18-12-06
", header=T)
library(dplyr)
library(lubridate)
df %>%
group_by(ID) %>%
mutate(ActivationDate = min(ymd(PaymentDate))) %>%
ungroup()
# # A tibble: 10 x 3
# ID PaymentDate ActivationDate
# <int> <fct> <date>
# 1 1 18-01-01 2018-01-01
# 2 1 18-02-03 2018-01-01
# 3 2 18-04-03 2018-04-03
# 4 2 18-05-08 2018-04-03
# 5 2 18-06-06 2018-04-03
# 6 3 17-12-23 2017-12-23
# 7 3 18-01-22 2017-12-23
# 8 3 18-02-24 2017-12-23
# 9 4 17-11-09 2017-11-09
#10 4 18-12-06 2017-11-09
假设您的数据集已经订购,并且您不想使用Date
格式,则可以使用
df %>%
group_by(ID) %>%
mutate(ActivationDate = first(PaymentDate)) %>%
ungroup()
使用data.table
的解决方案
数据:
df1<-
fread("ID Payment
1 18-01-01
1 18-02-03
2 18-04-03
2 18-05-08
2 18-06-06
3 17-12-23
3 18-01-22
3 18-02-24
4 17-11-09
4 18-12-06") %>% setDF
法典:
data.table::setDT(df1)[,Activation := Payment[1],by="ID"][]
结果:
# ID Payment Activation
#1: 1 18-01-01 18-01-01
#2: 1 18-02-03 18-01-01
#3: 2 18-04-03 18-04-03
#4: 2 18-05-08 18-04-03
#5: 2 18-06-06 18-04-03
#6: 3 17-12-23 17-12-23
#7: 3 18-01-22 17-12-23
#8: 3 18-02-24 17-12-23
#9: 4 17-11-09 17-11-09
#10: 4 18-12-06 17-11-09
快速提示:
- 切勿再在列名中使用"空格">
- 使用下划线或驼峰大小写。 例如:
payment_date
、paymentDate
使用sqldf
:
您的数据集:
df=read.table(text="ID PaymentDate
1 18-01-01
1 18-02-03
2 18-04-03
2 18-05-08
2 18-06-06
3 17-12-23
3 18-01-22
3 18-02-24
4 17-11-09
4 18-12-06",header=T)
法典
# we can first find the minimum PaymentDate using the inner query and then
# populate the data.frame using the inner query
sqldf("select a.ID,a.PaymentDate, b.ActivationDate from df as a JOIN
(select ID,min(PaymentDate) as ActivationDate from df group by ID) as b where a.ID=b.ID")
输出:
ID PaymentDate ActivationDate
1 1 18-01-01 18-01-01
2 1 18-02-03 18-01-01
3 2 18-04-03 18-04-03
4 2 18-05-08 18-04-03
5 2 18-06-06 18-04-03
6 3 17-12-23 17-12-23
7 3 18-01-22 17-12-23
8 3 18-02-24 17-12-23
9 4 17-11-09 17-11-09
10 4 18-12-06 17-11-09