Skip to content

Instantly share code, notes, and snippets.

@smrmkt
Last active December 20, 2015 19:08
Show Gist options
  • Save smrmkt/6180700 to your computer and use it in GitHub Desktop.
Save smrmkt/6180700 to your computer and use it in GitHub Desktop.
calcurate confidence/predict interval and plot with a result of regression
# import data
data <- read.delim(testadata.txt")
# execute regression and plot confidence/predict interval
predict_continue <- function(target_method, target_cpa, interval) {
d <- subset(data, method==target)
# regression using log() transformation
d.lm <- lm(continue~log(month)+cpa, data=d)
summary(d.lm)
# create prediction data
monthes <- seq(1, 100, 1)
cpas <- d$cpa
for (i in 1:(100-nrow(d))) cpas <- append(cpas, target_cpa)
methods <- target_method
for(i in 1:(100-1)) methods <- append(methods, target_method)
d.predict <- data.frame(month=monthes, cpa=cpas, method=methods)
# calcurate confidence interval and plot
if (span=="confidence") {
d.lm.conficence <- predict(d.lm, d.predict, interval="confidence")
plot(monthes, d.lm.conficence[,1], type="l", xlim=c(0,100), ylim=c(0,100), ylab="")
par(new=T)
plot(monthes, d.lm.conficence[,2], type="l", xlim=c(0,100), ylim=c(0,100), lty=2,col="red",ylab="")
par(new=T)
plot(monthes, d.lm.conficence[,3], type="l", xlim=c(0,100), ylim=c(0,100), lty=2,col="red",ylab="")
par(new=T)
plot(d$month, d$continue, type="p", xlim=c(0,100), ylim=c(0,100), lty=2, ylab="monthes", xlab="continue rate")
par(new=F)
}
# calcurate predict interval and plot
if (span=="predict") {
d.lm.predict <- predict(d.lm, d.predict, interval="prediction")
plot(monthes, d.lm.predict[,1], type="l", xlim=c(0,100), ylim=c(0,100), ylab="")
par(new=T)
plot(monthes, d.lm.predict[,2], type="l", xlim=c(0,100), ylim=c(0,100), lty=2,col="red",ylab="")
par(new=T)
plot(monthes, d.lm.predict[,3], type="l", xlim=c(0,100), ylim=c(0,100), lty=2,col="red",ylab="")
par(new=T)
plot(d$month, d$continue, type="p", xlim=c(0,100), ylim=c(0,100), lty=2, xlab="monthes", ylab="continue rate")
par(new=F)
}
return(d.lm.predict)
}
# execute function
predict.hoge.confidence <- predict_continue('hoge', 1000, 'confidence')
predict.hoge.predict <- predict_continue('hoge', 1000, 'predict')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment