library(stringr)
n=10;media=0;dt=1

generaMuestra=function (n,media=0,dt=1){
  muestra=rnorm(n,media,dt)
  media+(muestra-mean(muestra))/sd(muestra)*dt
}

generaResiduos=function (x,media=0,dt=1){
  e1=generaMuestra(length(x))
  e2=lm(e1 ~ x)$residuals
  media+(e2)/sd(e2)*dt
}

generaY=function(x,r,mediay=0,dty=1){
y = mediay+ ( (x-mean(x))/sd(x) * r + generaResiduos(x) * sqrt(1 - r^2))*dty
y
}

#x=generaMuestra(100,20,8)
#y=generaY(x,0.78,10,4)
#cor.test(x,y)
#plot(x,y)


n=1200
Edad=round(runif(n,min = 20,70),2)
#Latente=list(Depresion=round(generaMuestra(n),2))
Latente=list(Depresion=round(generaY(Edad,0.3),2))
Latente[["Ansiedad"]]=round(generaY(Latente[[1]],0.5),2)

df=data.frame(Individuo=1:n,Edad=Edad,Lat_Depresion=Latente[[1]],Lat_Ansiedad=round(Latente[[2]],2))


nitem=9
for(pre in names(Latente)){
  for(i in 1:nitem){
#    correlacion=runif(1,0.7,0.9)
    correlacion=seq(0.7,0.9,length.out = nitem)[i]
    variable=sprintf("%s_%d",pre,i)
    df[,variable]=round(generaY(Latente[[pre]],correlacion,5,1.5),0)
    df[df[,variable]<0,variable]=0
    df[df[,variable]>10,variable]=10
  }
}



nitem=9
for(pre in names(Latente)){
  for(i in 1:3){
    variable=sprintf("%sRepe_%d",pre,i)
    variableOrig=sprintf("%s_%d",pre,i)
    df[,variable]=df[,variableOrig]+rbinom(NROW(df),1,.2)*round(2*(rbinom(NROW(df),1,.5)-.5),0)
    df[df[,variable]<0,variable]=0
    df[df[,variable]>10,variable]=10
  }
}



for(i in 1:3){
  variable=sprintf("%s%s_%d",str_sub(names(Latente)[1],1,3),str_sub(names(Latente)[2],1,3),i)
  print(variable)
  v1=sprintf("%s_%d",names(Latente)[1],i)
  v2=sprintf("%s_%d",names(Latente)[2],i)
  df[,variable]=round((df[,v1]+df[,v2])/2+rnorm(NROW(df),0,.1),0)
  df[df[,variable]<0,variable]=0
  df[df[,variable]>10,variable]=10
}




library(xlsx)
write.xlsx2(df,"muestraConfirmatorio3.xlsx",row.names=F)



#
library(corrplot)
#mcor <- cor(df[,1+(1:(3+2*nitem))])

#pdf("confirmatorio-sectores.pdf",width = 10,height=10)
#par(mai=c(0,1,1,0))
#corrplot(mcor, type="upper", tl.col="black", tl.srt=45,method="number")
#corrplot(mcor, type="upper", tl.col="black", tl.srt=45,method="pie")
#corrplot(mcor, type="upper", order="hclust", tl.col="black", tl.srt=45)
#dev.off()
#dim(df)
