R.如何将sapply()应用于随机林

R.如何将sapply()应用于随机林,r,random-forest,R,Random Forest,我需要使用随机森林包的一批模型。我决定使用模型列表来存储它们。现在我不知道如何应用它们。我使用 list.of.models <- append(list.of.models, randomForest(data, as.factor(label)) 调用最后一个,但问题是randomForest返回一个包含许多值的列表,而不是学习者 如何添加到列表RF型号,然后调用它?例如,让我们看一段源代码 data(iris) set.seed(111) ind <- sample(2, n

我需要使用随机森林包的一批模型。我决定使用模型列表来存储它们。现在我不知道如何应用它们。我使用

list.of.models <- append(list.of.models, randomForest(data, as.factor(label))
调用最后一个,但问题是randomForest返回一个包含许多值的列表,而不是学习者

如何添加到列表RF型号,然后调用它?例如,让我们看一段源代码

data(iris)
set.seed(111)
ind <- sample(2, nrow(iris), replace = TRUE, prob=c(0.8, 0.2))
iris.rf <- randomForest(Species ~ ., data=iris[ind == 1,])
iris.pred <- predict(iris.rf, iris[ind == 2,])
数据(iris)
种子(111)

ind使用append,您正在使用RF.model中的元素扩展model.list,因此predict.randomForest等无法识别,因为外部容器列表及其属性class=“randomForest”丢失。此外,数据输入在predict.randomForest中命名为newdata

这应该起作用:

set.seed(1234)
library(randomForest)
data(iris)

test = sample(150,25)

#create 3 models
RF.models = lapply(1:3,function(mtry) {
    randomForest(formula=Species~.,data=iris[-test,],mtry=mtry)
})
#append extra model
RF.models[[length(RF.models)+1]] = randomForest(formula=Species~.,data=iris[-test,],mtry=4)
summary(RF.models)

#predict all models
sapply(RF.models,predict,newdata=iris[test,])

#predict one model
predict(RF.models[[length(RF.models)]],newdata=iris[test,])
尝试了do.call(predict,c(rf$call,data,type=“prob”))但在predict.randomForest(randomForest(x=data,y=as.factor(label)):指定的截止值不正确“head(sapply(rf$call,predict,neuverd,type=“prob”))中出现了一个错误,但在UseMethod(“predict”)中出现了错误:没有适用于类“name”的对象的“predict”方法
set.seed(1234)
library(randomForest)
data(iris)

test = sample(150,25)

#create 3 models
RF.models = lapply(1:3,function(mtry) {
    randomForest(formula=Species~.,data=iris[-test,],mtry=mtry)
})
#append extra model
RF.models[[length(RF.models)+1]] = randomForest(formula=Species~.,data=iris[-test,],mtry=4)
summary(RF.models)

#predict all models
sapply(RF.models,predict,newdata=iris[test,])

#predict one model
predict(RF.models[[length(RF.models)]],newdata=iris[test,])