1

I am trying to write a very simple function for my use of lavaan in order to obtain an effect from a very simple model. The code is below:

library(lavaan)
states <- as.data.frame(state.x77)

Effect<-function(dataset, X1, Y)
{
Model<-'
X1 ~~ X1; Y ~~Y;
Y ~ X1;'
fit<-lavaan(Model, dataset)
return(summary(fit))
}

When I call Effect(states, Murder, Income) or Effect(states, "Murder", "Income"), the following message displays:

"Error in lavaan(Model, dataset) : lavaan ERROR: missing observed variables in dataset: Y X1"

Everything is fine when I write the following though:

Model<-'
Murder ~~ Murder; Income ~~ Income;
Income ~ Murder;'
fit<-lavaan(Model, states)
summary(fit)

My guess is that lavaan() in my Effect function may indeed use the dataset "states", but that it is not equating X1 and Y with Murder and Income. Would someone have a clue on how I could solve this?

Many thanks,

  • Can you include a sample of what the state.x77 dataframe looks like? Your code is not reproducible without that data. Thanks! – fh432 Aug 06 '20 at 17:44

1 Answers1

0

The problem is, that the variables Y and X1 indeed are not part of the state.x77 data. The most straight forward way to do that would be to let the Effect function paste the model syntax using X1 and Y as character arguments; for example

data(state, package = "datasets")
states <- as.data.frame(state.x77)

Effect<-function(dataset, X1, Y)
{
  Model<-
  paste0(X1, "~~", X1, ";\n",
         Y, "~~", Y, ";\n",
         Y, "~~", X1, ";")  
  fit<-lavaan::lavaan(Model, dataset)
  return(lavaan::summary(fit))
}

Now Effect(states, X1 = "Murder", Y = "Income") should provide the desired results.

Tom
  • 934
  • 12
  • 20