我想以编程方式选择变量/为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”的公式。
答案 0 :(得分:1)
您可以将名称粘贴在一起:
as.formula(paste("cbind(", paste0(names(gc_lca), collapse = ","),")~ 1"))