2015-10-06 18 views
1

我用下面的代碼來創建主題模型的列表,其中主題數26〜35,按1:如何將僅有一個元素的「列表」的類更改爲R中的對象?

best.model <- lapply(seq(26,35, by=1), function(d){LDA(dtm2, d, method = "Gibbs", control = list(burnin = burnin, iter = iter, keep = keep))}) 

當我打電話best.model,我得到:

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

然後我嘗試每個主題模型提取到單獨的對象:

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] 

然而,當我調用類各型號的,我得到:

class(Gibbs26) 
[1] "list" 

如何從最初的best.model列表中提取每個元素,並讓每個元素成爲一個可以輕鬆操作的對象?

+3

見'「[」' - 一個單支架提取部分列表,'[',總是會返回另一個列表。嘗試使用雙括號:'[['。另見[這篇文章](http://stackoverflow.com/q/1169456/2572423) – JasonAizkalns

+1

看到這個鏈接 - https://twitter.com/hadleywickham/status/643381054758363136 – jeremycg

回答

2

你有兩個問題。首先由@JasonAizkalns在評論中提到的,你只使用一個支架,當你想要兩個:

Gibbs26 <- best.model[[1]] 

其次,你真的不希望被打字了很多事情,因爲你會不可避免地擰一個。相反,你可以使用lapplyassign來分配所有對象:?

lapply(1:length(bestmodel), function(x){assign(paste0("Gibbs", x + 25), bestmodel[[x]], envir = .GlobalEnv)}) 
+0

非常感謝,真的幫助 –

相關問題