I have a string that is built programmatically
tot=~item1+item2+item3+item4+item5+item6+item7+item8+item9+item10
that I need to wrap in two si
Generate data:
set.seed(101)
dat.test <- do.call(data.frame,replicate(6,sample(1:10, 50, replace=TRUE),
simplify=FALSE))
names(dat.test) <- paste0("s1.item",1:6)
myList1 <- list(scale1.tot=paste0("s1.item",1:6),
scale1.sub1=paste0("s1.item",1:3),
scale1.sub2=paste0("s1.item",4:6))
I only made one item here, but you could apply across a set of these too, with another *apply call or a for loop ...
This works (although it gives warnings because the data are trivial)
fitList <- mapply(function(lhs,rhs) {
mod <- paste(lhs,"=~",paste(rhs,collapse="+"))
cfa(mod,data=dat.test)
},
names(myList),myList)
I think you are misunderstanding R string syntax. The string you described is:
# this is what I want
mod <- '
tot=~item1+item2+item3+item4+item5+item6+item7+item8+item9+item10
'
That is exactly the same as writing:
mod <- '\ntot=~item1+item2+item3+item4+item5+item6+item7+item8+item9+item10\n'
or
mod <- "\ntot=~item1+item2+item3+item4+item5+item6+item7+item8+item9+item10\n"
Therefore, for your problem I think it would be sufficient to run:
string <- "tot=~item1+item2+item3+item4+item5+item6+item7+item8+item9+item10"
mod <- paste0("\n", string, "\n")
If you want to output your final model without the enclosing quotes, you can do:
cat(mod)
#
# tot=~item1+item2+item3+item4+item5+item6+item7+item8+item9+item10