r - 有没有办法使用 ', and "=~"的字符串公式创建 R 函数?

标签 r function stringr

我正在尝试创建一个 R 函数,让我指定潜在变量和指标。有没有办法将以下三行代码转换为函数?

            ' visual  =~ x1 + x2 + x3 
              textual =~ x4 + x5 + x6
              speed   =~ x7 + x8 + x9 '

我尝试使用paste和paste0,但效果不太好。例如,仅使用一个潜在变量,我尝试了以下方法:

myFunction <- function(z, x, ...) {
  latent_variable   <- paste0(x)
  latent_indicators <- paste0(..., collapse = " + ")
  latent_formula <- paste0(" ' ", latent_variable, "=", "~", latent_indicators, " ' ")
  
  fit <- cfa(latent_formula, data = z)
  
  summary(fit, fit.measures=TRUE)
}

myFunction(HolzingerSwineford1939, "visual", c("x1", "x2", "x3"))

但我收到此错误:

Error in lavParseModelString(model) : lavaan ERROR: left hand side (lhs) of this formula: 'visual =~ x1+x2+x3' contains either a reserved word (in R) or an illegal character: “'visual” See ?reserved for a list of reserved words in R Please use a variable name that is not a reserved word in R and use only characters, digits, or the dot symbol.

为了提供更多上下文,这是该函数将被使用的地方。请参阅下面的代码:

library(lavaan)
library(lavaanPlot)

HS.model <- ' visual  =~ x1 + x2 + x3 
              textual =~ x4 + x5 + x6
              speed   =~ x7 + x8 + x9 '

fit <- cfa(HS.model, data=HolzingerSwineford1939)

summary(fit, fit.measures=TRUE)
        
lavaanPlot(model = fit)

任何帮助将不胜感激。感谢您抽出时间。

最佳答案

您不应将单引号粘贴到公式中。您已经使用 paste() 构建了字符串。只需使用

latent_formula <- paste0(latent_variable, "=", "~", latent_indicators)

如果您想合并多个响应,这里有一个函数可以生成该公式

myFunction <- function(...) {
  params <- list(...)
  stopifnot(length(params)%%2==0)
  lefts = params[seq(1,length(params), by=2)]
  rights = params[seq(2,length(params), by=2)]
  rights <- Map(paste, rights, collapse="+")
  paste(paste0(lefts, " =~", rights), collapse="\n")
}

myFunction("visual", c("x1", "x2", "x3"), "textual", c("x4", "x5", "x6"), "speed", c("x7", "x8", "x9"))

关于r - 有没有办法使用 ', and "=~"的字符串公式创建 R 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62748018/

相关文章:

r - 减去子列表时如何使用lapply并使用str_extract函数

r - 在 R 中用另一个矩阵索引一个矩阵 - 索引越界

javascript - 如何用JS获取日期?

r - Gompertz R 中的老化分析

r - 软件包 ‘stringr’ 和 ‘stringi’ 的安装具有非零退出状态

r - 如何从R中的字符串中提取数字?

r - 在 r 中使用跨组聚合的加权平均值

r - x 实验室未显示完整?我应该如何设置参数?

r - 值更改(避免 0 1 到 1 2)

c++ - 在嵌套类中调用 `operator[]` 后保留类类型