I used the following code to create a list of topic models, in which the number of topics ranged from 26 to 35, by 1:
best.model <- lapply(seq(26,35, by=1), function(d){LDA(dtm2, d, method = "Gibbs", control = list(burnin = burnin, iter = iter, keep = keep))})
When I call best.model, I get:
> best.model
[[1]]
A LDA_Gibbs topic model with 26 topics.
[[2]]
A LDA_Gibbs topic model with 27 topics.
[[3]]
A LDA_Gibbs topic model with 28 topics.
[[4]]
A LDA_Gibbs topic model with 29 topics.
[[5]]
A LDA_Gibbs topic model with 30 topics.
[[6]]
A LDA_Gibbs topic model with 31 topics.
[[7]]
A LDA_Gibbs topic model with 32 topics.
[[8]]
A LDA_Gibbs topic model with 33 topics.
[[9]]
A LDA_Gibbs topic model with 34 topics.
[[10]]
A LDA_Gibbs topic model with 35 topics.
Then I try to extract each topic model into separate objects:
Gibbs26 <- best.model[1]
Gibbs27 <- best.model[2]
Gibbs28 <- best.model[3]
Gibbs29 <- best.model[4]
Gibbs30 <- best.model[5]
Gibbs31 <- best.model[6]
Gibbs32 <- best.model[7]
Gibbs33 <- best.model[8]
Gibbs34 <- best.model[9]
Gibbs35 <- best.model[10]
However, when I call the class of each model, I get:
class(Gibbs26)
[1] "list"
How do I extract each element from the initial best.model list, and have each element be an object that I can easily manipulate?
You have two problems. Firstly as mentioned by @JasonAizkalns in the comments, you are only using a single bracket when you want two:
Gibbs26 <- best.model[[1]]
Secondly, you don't really want to be typing out that many things, as you'll inevitably screw one up. Instead, you can use lapply
and assign
to assign all your objects:
lapply(1:length(bestmodel), function(x){assign(paste0("Gibbs", x + 25), bestmodel[[x]], envir = .GlobalEnv)})