我将%Y-%m格式化为一个因子,共有24个级别。数据通过几个月内的汇总活动进行格式化。
MemberID Month_Yr freq
1 2010-01 3
1 2010-03 6
2 2010-01 1
2 2010-05 2
3 2011-03 4
4 2010-02 1
我希望通过计算最旧和最新有效日期之间的差值来计算客户活跃的总月数。
现在,我已经尝试过:
month.aggregated$MonthlyAverage <- ave(month.aggregated$freq, month.aggregated$ï..MemberID)
,因为有些月份客户处于非活动状态,所以无法返回正确的值。我不知何故需要代码中包含的级别总数。
有什么想法吗?
答案 0 :(得分:0)
您可以像这样从因子水平计算月数:
n_months <- 12 * as.numeric(substr(Month_Yr, 1, 4)) + as.numeric(Month_Yr, 6, 7))
这样您就可以计算自记录开始以来的月份:
df$month_count <- n_months - min(n_months)
,您可以使用dplyr来获得汇总差异:
library(dplyr)
df %>% group_by(MemberID) %>% summarize(months_active = max(month_count) - min(month_count))