Skip to content

Instantly share code, notes, and snippets.

@cigrainger
Created March 24, 2014 10:17
Show Gist options
  • Select an option

  • Save cigrainger/9737671 to your computer and use it in GitHub Desktop.

Select an option

Save cigrainger/9737671 to your computer and use it in GitHub Desktop.
library(ggplot2)
library(reshape2)
library(RColorBrewer)
sales <- c(100,84,34,27,43,17,278,92,41,88,52,30,108,201,195,117,38,26,272,110,412,191,264,71,430,219,288,191,325,81)
cumsales <- c(1643,84,34,27,43,17,278,92,41,88,52,30,108,201,195,117,38,26,272,110,412,191,264,71,430,219,288,191,325,81)
cumsales <- cumsum(cumsales)
TSEP11 <- 1:30
Tdelt <- 1:180
Bass.nls <- nls(sales ~ M * ( ((P+Q)^2 / P) * exp(-(P+Q) * TSEP11) ) /(1+(Q/P)*exp(-(P+Q)*TSEP11))^2, start = list(M=max(cumsales), P=0.01, Q=0.3))
Bcoef <- coef(Bass.nls)
m <- Bcoef[1]
p <- Bcoef[2]
q <- Bcoef[3]
Bstde <- coef(summary(Bass.nls))[,2]
mup <- m + Bstde[1]
mlow <- m - Bstde[1]
pup <- p + Bstde[2]
plow <- p - Bstde[2]
qup <- q + Bstde[3]
qlow <- q - Bstde[3]
ngete <- exp(-(p+q) * Tdelt)
ngeteup <- exp(-(pup+qup) * Tdelt)
ngetelow <- exp(-(plow+qlow) * Tdelt)
Bpdf <- 2100000 * ( (p+q)^2 / p ) * ngete / (1 + (q/p) * ngete)^2
Bpdfup <- 2100000 * ( (pup+qup)^2 / pup ) * ngeteup / (1 + (qup/pup) * ngeteup)^2
Bpdflow <- 2100000 * ( (plow+qlow)^2 / plow ) * ngetelow / (1 + (qlow/plow) * ngetelow)^2
Bcdf <- 2100000 * (1 - ngete)/(1 + (q/p)*ngete)
Bcdfup <- 2100000 * (1 - ngeteup)/(1 + (qup/pup)*ngeteup)
Bcdflow <- 2100000 * (1 - ngetelow)/(1 + (qlow/plow)*ngetelow)
pdf <- data.frame(Tdelt,Bpdf,Bpdfup,Bpdflow)
cdf <- data.frame(Tdelt,Bcdf,Bcdfup,Bcdflow)
pdf <- melt(pdf,id.vars='Tdelt')
cdf <- melt(cdf,id.vars='Tdelt')
pdf$year <- pdf$Tdelt/12
cdf$year <- cdf$Tdelt/12
grpalette <- brewer.pal(3,'Greens')
ggplot(cdf,aes(x=year,y=value,colour=variable)) + geom_line(size=1.2) + scale_colour_manual(values=grpalette,name="Parameter\nestimates",labels=c('Mean','Upper','Lower')) + ylab('Cumulative sales') + xlab('Years from 2011') + ggtitle('Cumulative Adopters') + theme(plot.title = element_text(lineheight=.8, face="bold"))
ggplot(pdf,aes(x=year,y=value,colour=variable)) + geom_line(size=1.2) + scale_colour_manual(values=grpalette,name="Parameter\nestimates",labels=c('Mean','Upper','Lower')) + ylab('Sales per Month') + xlab('Years from 2011') + ggtitle('Per Month Adopters') + theme(plot.title = element_text(lineheight=.8, face="bold"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment