潜在 Class 分析 (poLCA) 以编程方式在 R 中创建公式

Latent Class Analysis (poLCA) Programmatically Creating Formula in R

我想以编程方式 select variables/create poLCA 函数的公式。当我需要使用“~ 1”时,问题似乎出现了。否则,制作公式是微不足道的。

下面,formula_lca 会起作用,因为我手动输入了变量。我更愿意用代码指定变量。我留下了一些导致错误的公式尝试。

if(!"pacman" %in% rownames(installed.packages())) {
  install.packages("pacman")
}
pacman::p_load(tidyverse, poLCA, caret)

data("GermanCredit")
gc <- GermanCredit

categorical_vars <- gc %>%
   keep(is.numeric) %>%
   keep( ~ sd(.x) < .50) %>%
   names(.) %>%
   sort(.)

lca_vars <- categorical_vars[str_detect(categorical_vars, "Employment|Job|Credit|Checking")]

# poLCA will not take zeroes; change values based on 1 index for each variable
gc_lca <- gc[, lca_vars] %>%
  map_df( ~ ifelse(.x == 0, 1, 2))

formula_lca = cbind(CheckingAccountStatus.0.to.200, CheckingAccountStatus.lt.0) ~ 1

as.formula(cbind(sym(str_c(lca_vars, collapse = ", "))), 1)
#> Error in formula.default(object, env = baseenv()): invalid formula

as.formula(paste0(lca_vars) ~ 1)
#> paste0(lca_vars) ~ 1

as.formula(paste("y ~ ", paste(cbind(lca_vars), collapse = ", ")))
#> Error in parse(text = x, keep.source = FALSE): <text>:1:36: unexpected ','
#> 1: y ~  CheckingAccountStatus.0.to.200,
#>                                        ^

set.seed(231213)
results.2 = poLCA(
  formula_lca,
  gc_lca,
  nclass = 2,
  nrep = 10,
  tol = .001,
  verbose = FALSE,
  graphs = FALSE
)

编辑:一个简单的补丁是 运行:

names(gc_lca) %>% str_c(collapse = ", ")

然后复制并粘贴不带引号的名称。不过我还是很好奇能不能构造一个外面带“~1”的公式

您可以将名称粘贴在一起:

as.formula(paste("cbind(", paste0(names(gc_lca), collapse = ","),")~ 1"))