How to return multiple objects of a library in R?

137 views Asked by At

I'm using rpart library in R. In a function, I want to return an array of rpart objects which are generated in a for loop. However, I don't know which data structure I should use for storing rpart objects. Each of the rpart objects has many values. Below you may see the code that generates rpart objects:

rpart.fit <- rpart(result ~ . , data = this.data , 
               subset = train.index, method= "class", 
               control=rpart.control(maxdepth=1))
1

There are 1 answers

5
JohannesNE On
library(rpart)

this.data <- data.frame(result = runif(20), var = runif(20))

foo <- function(data){
        aa <- list()
        for(i in 1:10){
                aa[[paste("model", i, sep="")]] <- rpart(result ~ var , data = this.data)

        }
        aa
}

bar <- foo(this.data)

plot(bar$model1)
plot(bar$model5)

Edit: Updated the function to dynamicly compute a name for the model.