[R] Help RFM analysis in R (i want a code where i can define my own breaks instead of system defined breaks used in auto_RFM package)
Jim Lemon
drjimlemon at gmail.com
Fri Oct 6 12:22:48 CEST 2017
Hi Hemant,
I had a chance to look at this. Here is a function that allows you to
rank customers on the raw values of recency, frequency and monetary. I
added the code for cutting the raw values into intervals, but haven't
had a chance to test it and I can't test it right now. It may be
helpful.
rfm_df<-read.table("rfm.csv",header=TRUE,sep="\t",stringsAsFactors = FALSE)
# expects a three (or more) column data frame where
# column 1 is customer ID, column 2 is amount of purchase
# and column 3 is date of purchase
qdrfm<-function(x,rbreaks=NULL,fbreaks=NULL,mbreaks=NULL,
date.format="%Y-%m-%d") {
today<-as.Date(date(), "%a %b %d %H:%M:%S %Y")
x$rscore<-today-as.Date(x[,3],date.format)
if(!is.null(rbreaks))
x$rscore<-cut(x$rscore,breaks=rbreaks,labels=FALSE)
custIDs<-unique(x[,1])
ncust<-length(custIDs)
rfmout<-data.frame(custID=custIDs,rscore=rep(0,ncust),
fscore=rep(0,ncust),mscore=rep(0,ncust))
rfmout$rscore=rank(by(x$rscore,x[,1],min))
if(!is.null(fbreaks)) rfmout$fscore<-rank(by(x[,3],x[,1],length))
else
rfmout$fscore<-cut(by(x[,3],x[,1],length),breaks=fbreaks,labels=FALSE)
if(!is.null(mbreaks)) rfmout$mscore<-rank(by(x[,2],x[,1],sum))
else
rfmout$mscore<-cut(by(x[,2],x[,1],sum),breaks=mbreaks,labels=FALSE)
rfmout$cscore<-rank((order(rfmout$rscore)+
order(rfmout$fscore,decreasing=TRUE)+
order(rfmout$mscore,decreasing=TRUE))/3)
rfmout$cscore<-rfmout$cscore-min(rfmout$cscore)+1
return(rfmout[order(rfmout$cscore),])
}
qdrfm(rfm_df,date.format="%m/%d/%Y")
Jim
More information about the R-help
mailing list