File: fit_indices.R

package info (click to toggle)
r-cran-regsem 1.6.2+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 496 kB
  • sloc: cpp: 263; ansic: 15; makefile: 2
file content (261 lines) | stat: -rw-r--r-- 6,181 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#'
#'
#' Calculates the fit indices
#' @param model regsem model object.
#' @param CV cross-validation. Note that this requires splitting the dataset
#'           into a training and test set prior to running the model. The
#'           model should be run on the training set, with the test set
#'           held out and then passed to CovMat=.
#' @param CovMat If CV=T then test covariance matrix must be supplied. Note
#'        That this should be done before running the lavaan model and should
#'        not overlap with the data or covariance matrix used to run the model.
#' @param data supply the dataset?
#' @param n.obs Number of observations in the test set for CV.
#' @keywords fit chisq ncp rmsea
#' @export
#' @examples
#' \dontrun{
#' fit_indices()
#' }


fit_indices =  function(model,CV=F,CovMat=NULL,data=NULL,n.obs=NULL){

  res <- list()
  ret <- as.vector(rep(0,24))

  names(ret) <- c("Fmin","p","chisq","p.chisq","nfac","df","npar","N","baseline.chisq","baseline.df",
                  "logl","ncp","rmsea","rmsea.lower","rmsea.upper","rmsea.pval","srmr",
                  "CFI","TLI","BIC","AIC",
                  "CAIC","EBIC.5","EBIC.25")





  p=model$nvar
  ret["p"] = p
  nfac = model$nfac
  ret["nfac"] = nfac
  df = model$df
  ret["df"] = df
  npar = model$npar
  ret["npar"] = npar

  if(CV==F){
    N = model$N
    ret["N"] = N
  }else{
    if(is.null(n.obs)){
      stop("For CV, need to provide sample size of test data")
    }
    N = n.obs
    ret["N"] = N
  }


  if(CV==F){
    fit = model$fit
    res$Data_Type = "Train"
    SampCov = model$SampCov
    if(model$mean==TRUE){
      ImpCov = model$Imp_Cov1
      SampCov2 = model$SampCov2
    }else{
      ImpCov = model$Imp_Cov
      SampCov2 = SampCov
    }
  }else if(CV==T){
    if(is.null(CovMat) ==T){
      stop("Need to Provide Test CovMat")
    }
    res$Data_Type = "Test"

    #dat <- model$data
  # ids <-  sample(nrow(dat),nrow(dat)/2)
    SampCov <- SampCov2 <- CovMat


    if(model$mean==TRUE){
      ImpCov = model$Imp_Cov1
    }else{
      ImpCov = model$Imp_Cov
    }

   # SampCov=CovMat
    fit = 0.5*(log(det(ImpCov)) + trace(SampCov %*% solve(ImpCov)) - log(det(SampCov))  - p)
  }#else if(CV=="boot"){
   # fit.rep <- rep(NA,n.boot)
   # ImpCov = model$Imp_Cov
   # SampCov = model$SampCov
   # data <- model$data
    #data = model@Data@X[[1]]
   #   for(i in 1:n.boot){

   #     ids <- sample(nrow(data),nrow(data),replace=TRUE)
   #     new.dat <- data[ids,]
   #     SampCov.boot <- cov(new.dat)
   #     fit.rep[i] = 0.5*(log(det(ImpCov)) + trace(SampCov.boot %*% solve(ImpCov)) - log(det(SampCov.boot))  - p)

   #   }
   # fit = mean(fit.rep)
   # varFit = var(fit.rep)
 # }



  ret["Fmin"] = fit

 # if(CV=="boot"){
 #   ret["varFit"] = varFit
 # }else{
 #   ret["varFit"] = 0
 # }

  chisq = fit*N*2
  ret["chisq"] = chisq




  if(model$lav.model@Fit@converged == FALSE){
    baseline.chisq = NA
    baseline.df = NA
  }else{
    lav.fits <- fitmeasures(model$lav.model)
    baseline.chisq = lav.fits["baseline.chisq"]
    baseline.df = lav.fits["baseline.df"]
  }


  #baseline.chisq = model$baseline.chisq
  ret["baseline.chisq"] = baseline.chisq
  #baseline.df = model$baseline.df
  ret["baseline.df"] = baseline.df


#  c <- N*p/2 * log(2 * pi)



  if(model$lav.model@Fit@converged == FALSE){
    logl_sat = NA
  }else{
    logl_sat <- as.numeric(lav.fits["unrestricted.logl"])
  }
  #logl_sat = model$logl_sat# -c -(N/2) * log(det(SampCov)) - (N/2)*p
  logl = -N * (fit- logl_sat/N)
  ret["logl"] = logl




    d = function(chisq,df,N) max(0,(chisq -df)/(N-1))
    ncp = d(chisq,df,N)
    ret["ncp"] = ncp


    pp <- try(pchisq(chisq,df))
    if(inherits(pp, "try-error")) {
      ret["p.chisq"] <- NA
    }else{
      ret["p.chisq"] <- 1-pp
      }




    rmsea = function(ncp,df) sqrt(ncp/df)
    ret["rmsea"] = max(rmsea(ncp,df),0)


    lower.lambda <- function(lambda) {
      (pchisq(chisq, df=df, ncp=lambda) - 0.95)
    }

    lambda.l <- try(uniroot(f=lower.lambda, lower=0, upper=chisq)$root,
                    silent=TRUE)
    if(inherits(lambda.l, "try-error")) {
      ret["rmsea.lower"] = NA
    }else{
      ret["rmsea.lower"] = sqrt( lambda.l/(N*df))
      }


    upper.lambda <- function(lambda) {

      ppp <- try(pchisq(chisq, df=df, ncp=lambda))
      if(inherits(pp, "try-error")) {
        NA
      }else{
        ppp-0.05
      }
    }

    lambda.u <- try(uniroot(f=upper.lambda, lower=0,upper=100)$root,
                    silent=TRUE)
    if(inherits(lambda.u, "try-error")){
      ret["rmsea.upper"] = NA
    }else{
      ret["rmsea.upper"] = sqrt( lambda.u/(N*df))
    }




    pppp <- try(pchisq(chisq, df=df, ncp=(N*df*0.05^2)))
    if(inherits(pp, "try-error")) {
      ret["rmsea.pval"] <- NA
    }else{
      ret["rmsea.pval"] <- 1-pppp
    }


    #srmr
    imp = cov2cor(ImpCov);obs = cov2cor(SampCov2)
    lobs <-  obs[!lower.tri(obs)]
    limp <-  imp[!lower.tri(imp)]
    ret["srmr"] <- sqrt(mean((limp - lobs)^2))

    BIC<- function(logl,N,df,p){
      -2*(logl) + log(N)*npar
    }
    ret["BIC"]= BIC(logl,N,df,p)


    AIC<- function(logl,df,p){
      -2*(logl) + 2*npar
    }
    ret["AIC"] = AIC(logl,df,p)


    CAIC<- function(logl,df,N){
      -2*(logl) + log(N+1) * df
    }
    ret["CAIC"] = CAIC(logl,df,N)


    EBIC<- function(logl,df,N,p,nfac,delta){
      -2*(logl) + log(N) * df + 2*df * delta * log(p * nfac)
    }
    ret["EBIC.5"] = EBIC(logl,df,N,p,nfac,0.5)
    ret["EBIC.25"] = EBIC(logl,df,N,p,nfac,0.25)

    ncp.null = d(baseline.chisq,baseline.df,N)
    CFI <- function(ncp.null,ncp){
      (ncp.null - ncp) / ncp.null
    }
    ret["CFI"] = CFI(ncp.null,ncp)

    TLI <- function(baseline.chisq,baseline.df,chisq,df){
      (baseline.chisq/baseline.df - chisq/df) / (baseline.chisq/baseline.df - 1)
    }
    ret["TLI"] = TLI(baseline.chisq,baseline.df,chisq,df)

  res$fits <- round(ret,5)
    #ret
  res
}