简体   繁体   中英

Removing double quote from string vector - poLCA application in R

I am trying to run latent class analysis using poLCA package in R. I have 284 variables (columns). Writing all data frame arguments (columns) one by one is cumbersome and not desirable. I am looking for a way to write columns concisely without much typing. I have generated the sample data frame below which I use to fit a simple LCA model:

library(poLCA);
set.seed(134);

#data

df<-as.data.frame(cbind(v1=rbinom(100, 1, 0.2)+1,
v2=rbinom(100,1,0.4)+1,
v3=rbinom(100,1,0.3)+1,
v4=rbinom(100, 1, 0.2)+1,
v5=rbinom(100,1,0.1)+1,
v6=rbinom(100,1,0.35)+1,
v7=rbinom(100, 1, 0.25)+1,
v8=rbinom(100,1,0.45)+1,
v9=rbinom(100,1,0.32)+1,
v10=rbinom(100, 1, 0.29)+1));

#poLCA model estimation - runs fine

f1<-cbind(v1,v2,v3,v4,v5,v6,v7,v8,v9,v10)~1;
system.time(fit<-poLCA(f1,data=df, nclass=3, maxiter=1000, graphs=FALSE,
tol=1e-10, na.rm=TRUE, probs.start=NULL));

#Instead of typing v1, v2, v3,.....,v10 in the formula 'f1' above, I re-wrote 'f1' 
as follows:

f2<-cbind(paste("v", c(1:10), sep=""))~1

#The above formula, 'f2', however combines all data frame arguments (columns) with
"double quote" wrapped around. Entering this formula inside poLCA function generates 
errors as "non-numeric arguments with mathematical function".  

#Thus, poLCA function below generates errors because f2 was not created correctly!!!

system.time(fit<-poLCA(f2, data=df, nclass=3, maxiter=1000, graphs=FALSE,
tol=1e-10, na.rm=TRUE, probs.start=NULL));   

How can I create f2 equivalent of f1 above? I highly appreciate your response. Thank you.

(Systems Information: "R version 3.1.0; "x86_64-w64-mingw32"; "poLCA_1.4.1")

Very bad solution. At least it works, but I'm sure there is a more correct way of doing this.

f2 = as.formula(paste("cbind(", paste("v", c(1:10), sep = "", collapse = ","), ")~1", sep ="", collapse=""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM