有没有一种使用带有'和'的字符串公式创建R函数的方法.=〜&quot ;? [英] Is there a way to create an R function using a string formula with ', and " =~"?

查看:57
本文介绍了有没有一种使用带有'和'的字符串公式创建R函数的方法.=〜&quot ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create an R function that lets me specify latent variables and indicators. Is there a way to convert the following three code lines into a function?

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

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

I tried using paste and paste0 but it didn't work very well. For example, using just one latent variable, I tried this:

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"))

但是我遇到了这个错误:

But I'm getting this error:

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.

要提供更多上下文,请在此处使用该函数.请参见下面的代码:

To give more context, this is where the function will be used. Please see code below:

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)

任何帮助将不胜感激.谢谢您的时间.

Any help will be appreciated. Thank you for your time.

推荐答案

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

You should not be pasting the single quotes into your formula. You are building the string already with paste(). Just use

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

如果您要合并多个响应,则此函数将生成该公式

If you wanted to combine more than one responts, here's a function that will generate that formula

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函数的方法.=〜&quot ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆