Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending models to list

Tags:

r

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?

like image 455
dzhioev Avatar asked Oct 09 '11 20:10

dzhioev


3 Answers

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"
like image 179
Josh Avatar answered Nov 10 '22 21:11

Josh


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)
like image 36
Andrie Avatar answered Nov 10 '22 19:11

Andrie


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))
like image 2
Nick Sabbe Avatar answered Nov 10 '22 19:11

Nick Sabbe