File: sCorrect-effects2.R

package info (click to toggle)
r-cran-lavasearch2 2.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,832 kB
  • sloc: cpp: 28; sh: 13; makefile: 2
file content (285 lines) | stat: -rw-r--r-- 13,421 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
### effects2.R --- 
##----------------------------------------------------------------------
## Author: Brice Ozenne
## Created: mar  4 2019 (10:28) 
## Version: 
## Last-Updated: jan 23 2024 (10:24) 
##           By: Brice Ozenne
##     Update #: 386
##----------------------------------------------------------------------
## 
### Commentary: 
## 
### Change Log:
##----------------------------------------------------------------------
## 
### Code:

## * effects2 (documentation)
#' @title Effects Through Pathways With Small Sample Correction 
#' @description Test whether a path in the latent variable model correspond to a null effect.
#' Similar to \code{lava::effects} but with small sample correction (if any).
#' So far it only work for a single path related two variable composed of one or two edges.
#' @name effects2
#'
#' @param object a \code{lvmfit} or \code{lvmfit2} object (i.e. output of \code{lava::estimate} or \code{lavaSearch2::estimate2}).
#' @param linfct [character vector] The path for which the effect should be assessed (e.g. \code{"A~B"}),
#' i.e. the effect of the right variable (B) on the left variable (A). 
#' @param robust [logical] should robust standard errors be used instead of the model based standard errors? Should be \code{TRUE} if argument cluster is not \code{NULL}.
#' @param cluster [integer vector] the grouping variable relative to which the observations are iid.
#' @param conf.level [numeric, 0-1] level of the confidence intervals.
#' @param from,to alternative to argument \code{linfct}. See \code{lava::effects}.
#' @param ssc [character] method used to correct the small sample bias of the variance coefficients: no correction (\code{"none"}/\code{FALSE}/\code{NA}),
#' correct the first order bias in the residual variance (\code{"residual"}), or correct the first order bias in the estimated coefficients \code{"cox"}).
#' Only relevant when using a \code{lvmfit} object. 
#' @param df [character] method used to estimate the degree of freedoms of the Wald statistic: Satterthwaite \code{"satterthwaite"}. 
#' Otherwise (\code{"none"}/\code{FALSE}/\code{NA}) the degree of freedoms are set to \code{Inf}.
#' Only relevant when using a \code{lvmfit} object. 
#' @param ... additional argument passed to \code{estimate2} when using a \code{lvmfit} object.
#' 
#' @details When argument object is a \code{lvmfit} object, the method first calls \code{estimate2} and then extract the confidence intervals.
#' 
#' @return A data.frame with a row per path.
#' 
#' @concept inference
#' @keywords smallSampleCorrection
#' @export
`effects2` <-
  function(object, linfct, robust, cluster, conf.level, ...) UseMethod("effects2")

## * effects2 (examples)
## TODO

## * effects2.lvmfit
#' @rdname effects2
#' @export
effects2.lvmfit <- function(object, linfct, robust = FALSE, cluster = NULL, conf.level = 0.95, to = NULL, from = NULL, df = lava.options()$df, ssc = lava.options()$ssc, ...){

    return(effects2(estimate2(object, ssc = ssc, df = df, dVcov.robust = robust, ...), linfct = linfct, to = to, from = from, robust = robust, cluster = cluster, conf.level = conf.level))

}

## * effects2.lvmfit2
#' @rdname effects2
#' @export
effects2.lvmfit2 <- function(object, linfct, robust = FALSE, cluster = NULL, conf.level = 0.95, to = NULL, from = NULL, ...){

    dots <- list(...)
    if(length(dots)>0){
        warning("Argument(s) \'",paste(names(dots),collapse="\' \'"),"\' not used by ",match.call()[1],". \n")
    }
    object0 <- object
    class(object0) <- setdiff(class(object0),"lvmfit2")
        
    ## ** identify path
    if(!is.null(to) || !is.null(from)){
        n.hypo <- 1

        if(!missing(linfct)){
            stop("Cannot specify argument \'linfct\' at the same time as argument \'from\' or \'to\'. \n")
        }
        e.effects <- effects(object0, from = from, to = to)
        pathEffect <- stats::setNames(list(stats::setNames(list(e.effects$path), paste0(e.effects["to"],"~",e.effects["from"]))),paste0(e.effects["to"],"~",e.effects["from"]))
        type <- "total"
        null <- 0

    }else{
        n.hypo <- length(linfct)
        pathEffect <- vector(mode = "list", length = n.hypo)
        if(is.null(names(linfct))){
            names(pathEffect) <- linfct
        }else{
            if(any(duplicated(names(linfct)))){
                stop("Duplicated names for argument \'linfct\'. \n")
            }
            names(pathEffect) <- names(linfct)
        }
        type <- rep(as.character(NA), n.hypo)
        null <- rep(as.numeric(NA), n.hypo)

        for(iH in 1:n.hypo){

            if(grepl("|",linfct[iH], fixed=TRUE)){
                type[iH] <- base::trimws(strsplit(linfct[iH],split="|",fixed=TRUE)[[1]][2], which = "both")
                type[iH] <- match.arg(type[iH], c("indirect","direct","total"))
                linfct[iH] <- strsplit(linfct[iH],split="|",fixed=TRUE)[[1]][1]
            }else{
                type[iH] <- "total"
            }
            
            ## extract left and right side of the equation
            if(length(grep("=",linfct[iH]))>1){
                stop("Each element of argument \'linfct\' should contain at most one \'=\' sign.\n",
                     "Something like: coef1-2*coef2=0. \n")
            }
            iContrast <- createContrast(linfct[iH])
            if(iContrast$null==0){
                iContrast <- createContrast(linfct[iH], rowname.rhs = FALSE)
            }

            null[iH] <- unname(iContrast$null)
            iLHS.hypo_factor <- as.double(iContrast$contrast)
            iLHS.hypo_coef <- unname(colnames(iContrast$contrast))
            iN.param <- length(iLHS.hypo_coef)

            pathEffect[[iH]] <- stats::setNames(vector(mode = "list", length = iN.param), iLHS.hypo_coef)
            attr(pathEffect[[iH]], "factor") <- iLHS.hypo_factor
            
            for(iCoef in 1:iN.param){ ## iCoef <- 1
                ## extract all paths for each coefficient
                pathEffect[[iH]][[iCoef]] <- effects(object0, stats::as.formula(iLHS.hypo_coef[[iCoef]]))$path
                if(length(pathEffect[[iH]][[iCoef]])==0){
                    stop("Could not find path relative to coefficient ",iLHS.hypo_coef[[iCoef]]," (linfct=",linfct[iH],"). \n")
                }else if(type[iH]=="direct" && any(sapply(pathEffect[[iH]][[iCoef]],length)>2)){
                    pathEffect[[iH]][[iCoef]] <- pathEffect[[iH]][[iCoef]][sapply(pathEffect[[iH]][[iCoef]],length)==2]
                    if(length(pathEffect[[iH]][[iCoef]])==0){
                        stop("Could not find direct path relative to coefficient ",iLHS.hypo_coef[[iCoef]]," (linfct=",linfct[iH],"). \n")
                    }
                }else if(type[iH]=="indirect" && any(sapply(pathEffect[[iH]][[iCoef]],length)>2)){
                    pathEffect[[iH]][[iCoef]] <- pathEffect[[iH]][[iCoef]][sapply(pathEffect[[iH]][[iCoef]],length)>2]
                    if(length(pathEffect[[iH]][[iCoef]])==0){
                        stop("Could not find indirect path relative to coefficient ",iLHS.hypo_coef[[iCoef]]," (linfct=",linfct[iH],"). \n")
                    }
                }
            }
            
        }
    }

    ## ** extract information
    ## 0-order: param
    object.param <- coef(object, as.lava = FALSE)
    object.paramAll <- coef2(object, type = 9, labels = 1)[,"Estimate"]
    name.param <- names(object.param)
    n.param <- length(name.param)

    ## 1-order: score
    if(robust){
        object.score <- score(object, cluster = cluster, as.lava = FALSE)
    }

    ## 2-order: variance covariance
    object.vcov.param <- vcov(object, as.lava = FALSE)
    if(robust){
        object.rvcov.param <- vcov(object, robust = TRUE, cluster = cluster, as.lava = FALSE)
    }
    
    test.df <- (object$sCorrect$df == "satterthwaite")
    if(test.df){
        object.dVcov.param <- object$sCorrect$dVcov.param

        if(robust && (lava.options()$df.robust != 1)){

            if(!is.null(cluster)){ ## update derivative according to cluster
                object.dRvcov.param <- .dRvcov.param(score = object.score,
                                                     hessian = hessian2(object, cluster = cluster),
                                                     vcov.param = object.vcov.param,
                                                     dVcov.param = object.dVcov.param,
                                                     n.param = n.param,
                                                     name.param = name.param)
                                              
            }else{
                dRvcov.param <- object$sCorrect$dRvcov.param
            }
        }
    }

    coefEffect <- pathEffect

    ## ** identify coefficients corresponding to path
    for(iH in 1:n.hypo){ ## iH <- 1
        for(iCoef in 1:iN.param){ ## iCoef <- 1
            iN.path <- length(pathEffect[[iH]][[iCoef]])
            for(iPath in 1:iN.path){ ## iPath <- 1
                coefEffect[[iH]][[iCoef]][[iPath]] <- paste(pathEffect[[iH]][[iCoef]][[iPath]][-1], pathEffect[[iH]][[iCoef]][[iPath]][-length(pathEffect[[iH]][[iCoef]][[iPath]])], sep = lava.options()$symbols[1])
                if(any(coefEffect[[iH]][[iCoef]][[iPath]] %in% name.param) == FALSE){
                    stop("Incorrect path: ",paste(pathEffect[[iH]][[iCoef]][[iPath]], collapse="->"),"\n",
                         "Could not find coefficient: \"",paste(coefEffect[[iH]][[iCoef]][[iPath]][coefEffect[[iH]][[iCoef]][[iPath]] %in% name.param == FALSE], collapse = "\" \""),"\".\n")
                }
            }
        }
    }

    ## ** point estimate
    vec.beta <- stats::setNames(rep(NA, length = n.hypo), names(pathEffect))
    for(iH in 1:n.hypo){ ## iH <- 1
        iValue.param <- lapply(coefEffect[[iH]], function(iCoef){ ## for each coefficient (e.g. Y~E1 - Y~E2 = 0)
            iValue.path <- lapply(iCoef, function(iName){prod(object.paramAll[iName])}) ## get effect through each path corresponding to a coefficient (e.g. Y~E: Y~E and Y~X and X~E, i.e. \beta1 and \beta2*\beta3)
            return(do.call("sum", iValue.path)) ## return total effect (e.g. \beta1 + \beta2*\beta3)
        })
        if(is.null(attr(coefEffect[[iH]],"factor"))){
            vec.beta[iH] <- unlist(iValue.param)
        }else{
            vec.beta[iH] <- sum(attr(coefEffect[[iH]],"factor") * unlist(iValue.param))
        }
    }

    ## ** variance
    ## *** partial derivative
    dbeta.dtheta <- matrix(NA, nrow = n.hypo, ncol = n.param, dimnames = list(names(pathEffect), name.param))
    for(iH in 1:n.hypo){ ## iH <- 1
        iValue.param <- lapply(coefEffect[[iH]], function(iCoef){  ## iCoef <- coefEffect[[iH]][[1]] ## for each coefficient (e.g. Y~E1 - Y~E2 = 0)
            iDValue.path <- colSums(do.call(rbind,lapply(iCoef, function(iName){ ## iName <- iCoef[[1]] ## get derivative through each path corresponding to a coefficient (e.g. Y~E: Y~E and Y~X and X~E, i.e. \beta1 and \beta2*\beta3)
                iDeriv <- stats::setNames(rep(0, n.param), name.param)
                iDeriv[intersect(iName,name.param)] <- prod(object.paramAll[iName])/object.paramAll[intersect(iName,name.param)]
                return(iDeriv)
            })))
        })
        if(is.null(attr(coefEffect[[iH]],"factor"))){
            dbeta.dtheta[iH,] <- iValue.param[[1]]
        }else{
            dbeta.dtheta[iH,] <- attr(coefEffect[[iH]],"factor") %*% do.call(rbind,iValue.param)
        }   
    }

    if(robust){
        Mvcov.beta <- dbeta.dtheta %*% object.rvcov.param %*% t(dbeta.dtheta)
    }else{
        Mvcov.beta <- dbeta.dtheta %*% object.vcov.param %*% t(dbeta.dtheta)
    }

    ## ** compute df
    if(test.df){
        vec.df <- dfSigma(contrast = dbeta.dtheta,
                          score = object.score,
                          vcov = object.vcov.param,
                          rvcov = object.rvcov.param,
                          dVcov = object.dVcov.param,
                          dRvcov = object.dRvcov.param,
                          keep.param = dimnames(object.dVcov.param)[[3]],                            
                          type = if(robust){lava.options()$df.robust}else{1})
    }else{
        vec.df <- rep(0, n.hypo)
    }

    ## ** gather everything in glht object
    linfct2 <- diag(1, ncol = n.hypo, nrow = n.hypo)
    dimnames(linfct2) <- list(names(pathEffect),names(pathEffect))

    out <- list(model = object,
                linfct = linfct2,
                rhs = null,
                coef = vec.beta,
                vcov = Mvcov.beta,
                df = vec.df,
                alternative = "two.sided",
                type = NULL,
                robust = robust,
                ssc = object$sCorrect$ssc$type,
                grad = dbeta.dtheta,
                path = pathEffect,
                global = NULL)
    class(out) <- c("glht2","glht")

    ## ** export
    return(out)

}

## * effects.lvmfit2
#' @rdname effects2
#' @export
effects.lvmfit2 <- effects2.lvmfit2

######################################################################
### effects2.R ends here