Overview
在做实验的时候因为要用到随机森林,所以使用了R
中的randomForest
包,但在画图的时候报了一个非常诡异的错误。
1. 错误描述
下面是我引入randomForest
包之后的代码,这里省略了一些细节,只保留跟错误有关的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | ## randomforest library ( "randomForest" ) # randomforest调参 bestmtryMatrix <- tuneRF (train.bal[,-1],train.bal[,1], ntreeTry=100, stepFactor=1.5,improve=0.01, trace= TRUE ,plot= FALSE , dobest= FALSE ) bestmtryMatrix # 找到最佳参数 bestmtry <- bestmtryMatrix[ which.min (bestmtryMatrix[,2]),1] # 训练模型 rfNormal <- randomForest (Class~.,data=train.bal, mtry=bestmtry, ntree=1000, keep.forest= TRUE , importance= TRUE ) # 预测 rfNormal.predictions <- predict (rfNormal,type= "prob" ,newdata=test) |
在画图时的代码:
1 2 3 4 5 6 7 | g <- ggplot(data=rocdata,aes(x=ejeX,y=ejeY))+geom_line(aes(colour=Metodo),size=0.8)+scale_colour_manual(values=c("red","blue","green4"))+xlab("False positive rate")+ ylab("True positive rate")+theme_custom()+theme(legend.position=c(0.73,0.1))+ #设定x,y轴坐标刻度 scale_x_continuous(limits=c(0, 1),breaks=seq(0,1,0.2))+ scale_y_continuous(limits=c(0, 1),breaks=seq(0,1,0.2)) # 添加一条对角线 g <- g+geom_abline(intercept=0,slope=1) |
上面代码中,theme_custom()
就是我自定义的样式函数,可以在 使用R语言ggplot2包画图时的一个不兼容问题 中查看这个函数的详细信息。
在运行时报了下面的错误:
1 2 3 | 错误于UseMethod("margin") : "margin"没有适用于"unit"目标对象的方法 Calls: theme_custom ... inherits -> theme -> element_text -> structure -> margin 停止执行 |
又是element_text
中margin
的问题,可见更新之后这里有点不稳定,我们在 使用R语言ggplot2包画图时的一个不兼容问题 讨论的问题也与margin
相关。
2. 解决方法
刚开始我以为是这个函数名在randomForest
中有同名函数导致冲突,所以修改了theme_custom()
,改为theme_custom_chris()
,结果依然报错。但是我试着删除了randomForest
的相关代码(library("randomForest")
这句也一定要删掉),则不再报错。
实际上,正是library("randomForest")
引入randomForest
包导致的问题,那在使用完randomForest
之后,手动将它从当前的程序中去掉是不是就可以了呢?
在R
中使用完randomForest
包的代码之后,ggplot画图代码之前,添加下面的代码:
1 | detach("package:randomForest", unload=TRUE) |
意义也非常直观明了,在运行过程中detach randomForest
包,然后重新运行程序,一切正常。