7

I have problem with creating list of models. Suppose I've created model:

> rp <- rpart(V41 ~ ., data=learnData, method="class")

If I'm creating list straight, thats OK:

> ll <- list(rp, rp, rp)
> class(ll[[1]])
[1] "rpart"
> class(ll[[2]])
[1] "rpart"
> class(ll[[3]])
[1] "rpart"

But if I'm trying to append model to already created list, models changing their class to data.frame:

> ll <- list(rp)
> ll <- append(ll, rp)
> class(ll[[1]])
[1] "rpart"
> class(ll[[2]])
[1] "data.frame"

What's a reason of this behavior and how can I append model to list?

dzhioev
  • 96
  • 1
  • 6
  • 18

3 Answers3

12

Andrie's solution:

x <- list(fit1)
x <- list(x, fit2)

doesn't work because it results in a list with list and lm components:

sapply(x,class)
# [1] "list" "lm"

you need to append a list to a list using c to get the desired behavior:

x <- list(fit1)
x <- c(x, list(fit2))
sapply(x,class)
# [1] "lm" "lm"
x <- c(x, list(fit3))
sapply(x,class)
# [1] "lm" "lm" "lm"
Josh
  • 121
  • 1
  • 2
5

The function append is used to add elements to a vector.

To add elements to a list, use list. Try:

fit1 <- lm(Sepal.Length ~ Sepal.Width, data=iris)
fit2 <- lm(Sepal.Length ~ Petal.Width, data=iris)

x <- list(fit1, fit2)
str(x, max.level=1)

List of 2
 $ :List of 12
  ..- attr(*, "class")= chr "lm"
 $ :List of 12
  ..- attr(*, "class")= chr "lm"

You should now have a list of lm objects:

> class(x[[1]])
[1] "lm"

To append to an existing list, use list as follows:

x <- list(fit1)
x <- list(x, fit2)
Andrie
  • 176,377
  • 47
  • 447
  • 496
2

Behind the scene, append simply works by using c (just type append and enter in the command line to see its source code). If you check the help for c, you'll find interesting things in the examples there (check the "do not use" part).

I remember this from a recent other question, or perhaps it was recently on R chat, but cannot recall which it was, so if somebody else can point to it?

In any case, for what you want:

ll<-c(ll, list(rp))

or if you insist on using append:

ll<-append(ll, list(rp))
Nick Sabbe
  • 11,684
  • 1
  • 43
  • 57