#内置数据集
#固定格式的数据(矩阵、数据框或一个时间序列等)
#统计建模、回归分析等试验需要找合适的数据集
#R内置数据集,存储在,通过
help(package="datasets")
#通过data函数访问这些数据集
data()
#得到新窗口 前面:数据集名字 后面:内容
#包含R所有用到的数据类型,包括:向量、矩阵、列表、因子、数据框以及时间序列等
#直接输入数据集的名字就可以直接使用这些数据集
#输出一个向量
rivers
#是北美141条河流长度
#这些数据集的名字都是内置的,一般我们在给变量命名时最好不要重复
#否则数据集在当前对话中会被置换掉
#例如
rivers<-c(1,2,3)
rivers
#不过影响不大
#再使用data函数重新加载这个数据集就可以了
data("rivers")
rivers
#一些常用内置数据集
#默认介绍页面只有名字和介绍,并没有给出数据分类
#哪些是向量、矩阵、数据框等?
#查看数据集除了直接敲数据集名字显示数据之外
#还可以使用help函数查看每个数据集具体的内容
help("mtcars")
euro
#欧元汇率,长度为11,每个元素都有命名
#输出向量的属性信息
names(euro)
#将5个数据构成一个数据框
向量
state.abb #美国50个州的双字母缩写
state.area #美国50个州的面积
state.name #美国50个州的全称
因子
state.division #美国50个州的分类,9个类别
state.region #美国50个州的地理分类
#
state<-data.frame(state.name,state.abb,state.area,state.division,state.region)
state
state.x77 #美国50个州的八个指标
state.x77
VADeaths #1940年弗吉尼亚州死亡率(每千人)
volcano #某火山区的地理信息(10米×10米的网格)
WorldPhones #8个区域在7个年份的电话总数
iris3 #3种鸢尾花形态数据
#以上矩阵→适合画热图
heatmap(volcano)
#这里只是作为一个演示,还需要对这个图进行一些调整
#更复杂的数据结构
Titanic #泰坦尼克乘员统计,是一个数组
UCBAdmissions #伯克利分校1973年院系、录取和性别的频数
crimtab #3000个男性罪犯左手中指长度和身高关系
HairEyeColor #592人头发颜色、眼睛颜色和性别的频数
occupationalStatus #英国男性父子职业联系
#类矩阵
eurodist #欧洲12个城市的距离矩阵,只有下三角部分
Harman23.cor #305个女孩八个形态指标的相关系数矩阵
Harman74.cor #145个儿童24个心理指标的相关系数矩阵
#R中内置最多的数据集——数据框
cars #1920年代汽车速度对刹车距离的影响
iris #3种鸢尾花形态数据
mtcars #32辆汽车在11个指标上的数据
rock #48块石头的形态数据
sleep #两药物的催眠效果
swiss #瑞士生育率和社会经济指标
trees #树木形态指标
USArrests #美国50个州的四个犯罪率指标
women #15名女性的身高和体重
#列表
state.center #美国50个州中心的经度和纬度
#类数据框
Orange #桔子树生长数据
#时间序列数据,和数据框类似,不同的是具有时间序列的顺序,是数据分析中非常常见的格式
#能反映出变化情况以及变化的趋势等
#因此有很多专门的方法用于时间序列的数据分析
co2 #1959-1997年每月大气co2浓度(ppm)
presidents #1945-1974年每季度美国总统支持率
uspop #1790–1970美国每十年一次的人口总数(百万为单位)
#除了内置数据集之外,许多R扩展包中也内置了很多数据集
#这些数据集作为扩展包的函数使用的案例
#加载R包之后这些数据集也同样被加载进来
#例如MASS包中的Cars93数据
#包含了27个变量,是1993年93辆汽车的型号指标
install.packages("MASS")
library("MASS")
help("Cars93")
#使用data函数在参数package中等于对应R包的名字,即可列出每个R包中包含的数据集
#ex
data(package="MASS")
#显示R中所有可用的数据集
data(package=.packages(all.available = TRUE))
#不加载R包使用其中的数据集
data(Chile,package="car")
Chile
#>data(Chile,package="car")
#Warning message:
# In data(Chile, package = "car") : data set ‘Chile’ not found
#>Chile
#Error: object 'Chile' not found
install.packages("car")
library("car")
help("Chile")
本文用到的处理二值数据的方法,有以下两种:glm(generalized boosted models)
glmnet(generalized linear models)
glm使用了boosted trees,glmnet使用了regression
# load libraries
library(caret)
library(pROC)
#################################################
# data prep
#################################################
# load data
titanicDF <- read.csv('http://math.ucdenver.edu/RTutorial/titanic.txt',sep='\t')
titanicDF$Title <- ifelse(grepl('Mr ',titanicDF$Name),'Mr',ifelse(grepl('Mrs ',titanicDF$Name),'Mrs',ifelse(grepl('Miss',titanicDF$Name),'Miss','Nothing')))
titanicDF$Age[is.na(titanicDF$Age)] <- median(titanicDF$Age, na.rm=T)
# miso format
titanicDF <- titanicDF[c('PClass', 'Age','Sex', 'Title', 'Survived')]
# dummy variables for factors/characters
titanicDF$Title <- as.factor(titanicDF$Title)
titanicDummy <- dummyVars("~.",data=titanicDF, fullRank=F)
titanicDF <- as.data.frame(predict(titanicDummy,titanicDF))
print(names(titanicDF))
# what is the proportion of your outcome variable?
prop.table(table(titanicDF$Survived))
# save the outcome for the glmnet model
tempOutcome <- titanicDF$Survived
# generalize outcome and predictor variables
outcomeName <- 'Survived'
predictorsNames <- names(titanicDF)[names(titanicDF) != outcomeName]
#################################################
# model it
#################################################
# get names of all caret supported models
names(getModelInfo())
titanicDF$Survived <- ifelse(titanicDF$Survived==1,'yes','nope')
# pick model gbm and find out what type of model it is
getModelInfo()$gbm$type
# split data into training and testing chunks
set.seed(1234)
splitIndex <- createDataPartition(titanicDF[,outcomeName], p = .75, list = FALSE, times = 1)
trainDF <- titanicDF[ splitIndex,]
testDF <- titanicDF[-splitIndex,]
# create caret trainControl object to control the number of cross-validations performed
objControl <- trainControl(method='cv', number=3, returnResamp='none', summaryFunction = twoClassSummary, classProbs = TRUE)
# run model
objModel <- train(trainDF[,predictorsNames], as.factor(trainDF[,outcomeName]),
method='gbm',
trControl=objControl,
metric = "ROC",
preProc = c("center", "scale"))
)
# find out variable importance
summary(objModel)
# find out model details
objModel
#################################################
# evalute mdoel
#################################################
# get predictions on your testing data
# class prediction
predictions <- predict(object=objModel, testDF[,predictorsNames], type='raw')
head(predictions)
postResample(pred=predictions, obs=as.factor(testDF[,outcomeName]))
# probabilites
predictions <- predict(object=objModel, testDF[,predictorsNames], type='prob')
head(predictions)
postResample(pred=predictions, obs=testDF[,outcomeName])
auc <- roc(ifelse(testDF[,outcomeName]=="yes",1,0), predictions[[2]])
print(auc$auc)
################################################
# glm model
################################################
# pick model gbm and find out what type of model it is
getModelInfo()$glmnet$type
# save the outcome for the glmnet model
titanicDF$Survived <- tempOutcome
# split data into training and testing chunks
set.seed(1234)
splitIndex <- createDataPartition(titanicDF[,outcomeName], p = .75, list = FALSE, times = 1)
trainDF <- titanicDF[ splitIndex,]
testDF <- titanicDF[-splitIndex,]
# create caret trainControl object to control the number of cross-validations performed
objControl <- trainControl(method='cv', number=3, returnResamp='none')
# run model
objModel <- train(trainDF[,predictorsNames], trainDF[,outcomeName], method='glmnet', metric = "RMSE")
# get predictions on your testing data
predictions <- predict(object=objModel, testDF[,predictorsNames])
library(pROC)
auc <- roc(testDF[,outcomeName], predictions)
print(auc$auc)
postResample(pred=predictions, obs=testDF[,outcomeName])
# find out variable importance
summary(objModel)
plot(varImp(objModel,scale=F))
# find out model details
objModel
# display variable importance on a +/- scale
vimp <- varImp(objModel, scale=F)
results <- data.frame(row.names(vimp$importance),vimp$importance$Overall)
results$VariableName <- rownames(vimp)
colnames(results) <- c('VariableName','Weight')
results <- results[order(results$Weight),]
results <- results[(results$Weight != 0),]
par(mar=c(5,15,4,2)) # increase y-axis margin.
xx <- barplot(results$Weight, width = 0.85,
main = paste("Variable Importance -",outcomeName), horiz = T,
xlab = "<(-) importance > <neutral > <importance (+) >", axes = FALSE,
col = ifelse((results$Weight >0), 'blue', 'red'))
axis(2, at=xx, labels=results$VariableName, tick=FALSE, las=2, line=-0.3, cex.axis=0.6)
################################################
# advanced stuff
################################################
# boosted tree model (gbm) adjust learning rate and and trees
gbmGrid <- expand.grid(interaction.depth = c(1, 5, 9),
n.trees = 50,
shrinkage = 0.01)
# run model
objModel <- train(trainDF[,predictorsNames], trainDF[,outcomeName], method='gbm', trControl=objControl, tuneGrid = gbmGrid, verbose=F)
# get predictions on your testing data
predictions <- predict(object=objModel, testDF[,predictorsNames])
library(pROC)
auc <- roc(testDF[,outcomeName], predictions)
print(auc$auc)