简体   繁体   中英

Random forest object not loading

I am saving two random forest objects as a rda files. When I load them- One loads as character and the other loads as randomForest object! Can someone explain this?

Here is my code snippet :

fit1 <- load("rfModel_pw2.rda")
fit2 <- load("rfModel_pw3.rda")
Pred1 <- predict(get(fit1), test, "prob")
#Error in get(fit1) : invalid first argument
Pred2 <- predict(get(fit2), test, "prob")
class(fit1)
#[1] "randomForest.formula" "randomForest" 
> class(fit2)
#[1] "character"

load() places loaded objects from .rda file in global environment automatically and returns only the character names of loaded objects. Instead of using get([name]) simply use the same object-name before saving and after loading, as in example. Otherwise if you like the loader function to return loaded object, you can replace load() / save() with saveRDS() / readRDS() .

library(randomForest)
X = replicate(2,rnorm(1000))
y = apply(X,1,sum) 
rf = randomForest(X,y)
save(rf,file="./rf.rda")

rm(list=ls())
load(file="./rf.rda") #object is restored in global enviroment by former name
predict(rf,replicate(2,rnorm(1000)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM