Reputation: 21
I have several RandomForest formulas named forest.1, forest.2, forest.3, etc. Would like to read them one by one using "for" iterations, for example:
for(i in 1:20){
model = forest.i
predict.y = predict(model, test.x)
}
Of course, forest.i (i from 1 to 20) cannot be recognized as 20 fomulas. What can I do to make it work? Thanks!
Upvotes: 2
Views: 54
Reputation: 25444
Try putting them into a list first:
forests <- list(
forest.1,
forest.2,
forest.3,
...,
forest.20
)
(Fill in the dots.) Then, you can simply do
for (model in forests) {
... # your code
}
If you don't want to type the 20 list entries, create a character vector with the values "forest.1"
till "forest.20"
and use mget
.
Upvotes: 0
Reputation: 70623
You can use function get
, e.g. model <- get(sprintf("forest.%i", i))
. This will create a string, e.g forest.1
and try to fetch an object with this name.
Upvotes: 2