我的 data.table
是这样的:
AccountNo SubscriptionStart SubscriptionEnd
11111 2010-10-12 2011-10-11
11112 2009-03-08 2010-03-08
11112 2010-03-08 2011-03-08
11112 2012-03-08 2013-03-08
11113 2011-08-21 2012-08-21
我想要实现的是添加一个新列来标记稍后更新的帐户。
换句话说:如果 SubscriptionEnd <= max(SubscritionStart) 在 AccountNo 定义的子集中,则 GotRenewed 为 TRUE。在这个例子中它会是这样的:
AccountNo SubscriptionStart SubscriptionEnd GotRenewed
11111 2010-10-12 2011-10-11 0
11112 2009-03-08 2010-03-07 1
11112 2010-03-08 2011-03-07 1
11112 2012-03-08 2013-03-07 0
11113 2011-08-21 2012-08-21 0
我怎样才能做到这一点?感谢您的帮助!
谢谢。
最佳答案
dt[,GotRenewed := SubscriptionEnd <= max(SubscriptionStart), by=AccountNo]
AccountNo SubscriptionStart SubscriptionEnd GotRenewed
1: 11111 2010-10-12 2011-10-11 FALSE
2: 11112 2009-03-08 2010-03-08 TRUE
3: 11112 2010-03-08 2011-03-08 TRUE
4: 11112 2012-03-08 2013-03-08 FALSE
5: 11113 2011-08-21 2012-08-21 FALSE
如果您确实需要 0/1,请使用 as.numeric
。
关于r - 使用聚合遍历 data.table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14979989/