如何将只有一个元素的 "list" 的 class 更改为 R 中的对象?

How do I change the class of a "list" with only one element, to an object in R?

我用下面的代码创建了一个主题模型列表,其中主题数量从26到35,乘以1:

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 时,我得到:

class(Gibbs26)
[1] "list"

如何从初始 best.model 列表中提取每个元素,并使每个元素成为我可以轻松操作的对象?

你有两个问题。首先,正如@JasonAizkalns 在评论中提到的,当你需要两个时,你只使用一个括号:

Gibbs26 <- best.model[[1]]

其次,您真的不想输入那么多内容,因为您不可避免地会搞砸。相反,您可以使用 lapplyassign 来分配所有对象:

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