0

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))
Pegah
  • 121
  • 1
  • 12

1 Answers1

0
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.

JohannesNE
  • 1,343
  • 9
  • 14
  • The problem here is that I have 50 models and it's not possible to make a string (like "model1") and assign an rpart object to it in the **for** loop. Even, the number of models is variable. – Pegah Jun 24 '15 at 11:55
  • When I use model attribute for list, I get this error: **no applicable method for 'predict' applied to an object of class "list"** , where _predict_ is a function I use rpart model as its argument. – Pegah Jun 24 '15 at 12:25
  • @Pegah, the error you note may come from trying to use the `predict` function on the list itself rather than on the _elements_ of the list, where each element is an `rpart` object. If `yourList` is a list of `rpart` objects, then `predict(yourList[[2]])` will give the result of `predict` on the second `rpart` object, as an example. – EdM Jun 24 '15 at 13:36
  • I still have the problem of attributes. How can I create a name for an attribute and assign an `rpart` object to it? In a `for` loop, how can I concatenate `modelX` to my `list` t times while each time using a different name for model attribute? `rlist <- c(rlist, modelX=rpart)` – Pegah Jun 24 '15 at 13:53
  • You can use "rlist[[string]] <-" in a for loop if you use paste() to make the string, i think you have what you want. See my updated answer. – JohannesNE Jun 25 '15 at 10:45