获取r中指定日期后剩余用户的百分比



我正在使用用户生成的数据集(假设它是应用程序用户数据或服务),我根据用户行为特征即使用频率对其进行聚类。我想知道有多少,或者百分比的用户在特定日期后停止使用应用程序/服务,以及他们来自哪个集群。

这里有一个可复制的例子,我希望是合适的:-

library(Pareto)
library(uuid)
library(ggplot2)
library(tidyverse)
library(data.table)
set.seed(1)
n_users <- 100
n_rows <- 3650
relative_probs <- rPareto(n = n_users, t = 1, alpha = 0.3, truncation = 500) 
unique_ids <- UUIDgenerate(n = n_users)
id_sample <- sample(unique_ids, size = n_rows, prob = relative_probs, replace = TRUE)
Date<-seq(as.Date("2015-01-01"), as.Date("2015-12-31"), by = "1 day")
Date<-sample(Date,size = n_rows,replace = T)
df<-data.frame(id_sample,Date)
df
df<-df%>%arrange(Date)

userData<-df%>%
group_by(id_sample)%>%
summarise(Count=n())
scaledData<-scale(userData[,2])
scaledData
set.seed(15)
clust<-kmeans(scaledData, centers=5, nstart = 15)
userData$Cluster<-clust$cluster
setDT(userData)[Cluster==1, ClusterName:="Cluster 1"]
userData[Cluster==2, ClusterName:="Cluster 2"]
userData[Cluster==3, ClusterName:="Cluster 3"]
userData[Cluster==4, ClusterName:="Cluster 4"]
userData[Cluster==5, ClusterName:="Cluster 5"]
user_vars<-userData%>%select(id_sample,ClusterName)
df<-merge(df,user_vars,by="id_sample")
df$Month<-lubridate::month(df$Date)
df%>%
group_by(Month)%>%
summarise(N_Users=n_distinct(id_sample))

我想知道是否有一个dplyr解决方案或类似的东西,我可以将日期设置为阈值,以查看在指定日期之前的数据中有多少用户(作为百分比或计数),在指定日期之后出现在集群级别。例如,捕获指定日期之前的所有唯一用户ID的解决方案,其结果显示在指定日期之后这些用户仍留在数据中的百分比(按集群级别分组)。

library(lubridate)
how_many=function(df, cluster, my_date) {
df1=df%>%filter(ClusterName==cluster)
before=filter(df1, Date<my_date) 
after=filter(df1,Date>my_date)
count=0
for (i in unique(before$id_sample)) {
if (i %in% after$id_sample) {
count=count+1
}
}
return(c(count, count/n_distinct(before$id_sample)))
}

该函数接受数据帧(df)、集群名称和要查看在该日期之后至少出现一次的日期之前唯一用户的比例/数量的日期。

how_many(df, "Cluster 4", make_date(2015, 05, 19))
39.0000000  0.9069767

最新更新