【发布时间】:2020-07-06 01:23:35
【问题描述】:
我正在尝试创建一个 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)
任何帮助将不胜感激。感谢您的宝贵时间。
【问题讨论】:
-
你能用R的公式吗,比如
visual ~ x1 + x2 + x3?使用它,它可以直接与其他 R 基本函数 (model.matrix?) 一起使用,而不是解析字符串。 -
@r2evans 这是个好主意。我还没有尝试过model.matrix。它可以与 =~ 一起使用吗?
-
不,R 中没有任何东西可以与
=~一起使用,但很多东西都可以与~一起使用:这是它自己的东西,formula。