我正在尝试创建一个 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/