/
VCOV.R
2714 lines (2179 loc) · 83.9 KB
/
VCOV.R
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#----------------------------------------------#
# Author: Laurent Berge
# Date creation: Thu Apr 01 10:25:53 2021
# ~: VCOV related stuff
#----------------------------------------------#
####
#### User-level ####
####
#' Computes the variance/covariance of a `fixest` object
#'
#' This function extracts the variance-covariance of estimated parameters from a model
#' estimated with [`femlm`], [`feols`] or [`feglm`].
#'
#' @inheritParams summary.fixest
#' @inheritParams nobs.fixest
#'
#' @param attr Logical, defaults to `FALSE`. Whether to include the attributes describing how
#' the VCOV was computed.
#' @param ... Other arguments to be passed to [`summary.fixest`].
#'
#' The computation of the VCOV matrix is first done in [`summary.fixest`].
#'
#' @details
#' For an explanation on how the standard-errors are computed and what is the exact meaning of
#' the arguments, please have a look at the dedicated vignette:
#' [On standard-errors](https://lrberge.github.io/fixest/articles/standard_errors.html).
#'
#' @seealso
#' You can also compute VCOVs with the following functions: [`vcov_cluster`],
#' [`vcov_hac`], [`vcov_conley`].
#'
#' @return
#' It returns a \eqn{K\times K} square matrix where \eqn{K} is the number of variables
#' of the fitted model.
#' If `attr = TRUE`, this matrix has an attribute \dQuote{type} specifying how this
#' variance/covariance matrix has been computed.
#'
#' @author
#' Laurent Berge
#'
#' @seealso
#' See also the main estimation functions [`femlm`], [`feols`] or [`feglm`].
#' [`summary.fixest`], [`confint.fixest`], [`resid.fixest`], [`predict.fixest`], [`fixef.fixest`].
#'
#' @references
#'
#' Ding, Peng, 2021, "The Frisch–Waugh–Lovell theorem for standard errors." Statistics & Probability Letters 168.
#'
#' @examples
#'
#' # Load panel data
#' data(base_did)
#'
#' # Simple estimation on a panel
#' est = feols(y ~ x1, base_did)
#'
#' # ======== #
#' # IID VCOV #
#' # ======== #
#'
#' # By default the VCOV assumes iid errors:
#' se(vcov(est))
#'
#' # You can make the call for an iid VCOV explicitly:
#' se(vcov(est, "iid"))
#'
#' #
#' # Heteroskedasticity-robust VCOV
#' #
#'
#' # By default the VCOV assumes iid errors:
#' se(vcov(est, "hetero"))
#'
#' # => note that it also accepts vcov = "White" and vcov = "HC1" as aliases.
#'
#' # =============== #
#' # Clustered VCOVs #
#' # =============== #
#'
#' # To cluster the VCOV, you can use a formula of the form cluster ~ var1 + var2 etc
#' # Let's cluster by the panel ID:
#' se(vcov(est, cluster ~ id))
#'
#' # Alternative ways:
#'
#' # -> cluster is implicitly assumed when a one-sided formula is provided
#' se(vcov(est, ~ id))
#'
#' # -> using the argument cluster instead of vcov
#' se(vcov(est, cluster = ~ id))
#'
#' # For two-/three- way clustering, just add more variables:
#' se(vcov(est, ~ id + period))
#'
#' # -------------------|
#' # Implicit deduction |
#' # -------------------|
#' # When the estimation contains FEs, the dimension on which to cluster
#' # is directly inferred from the FEs used in the estimation, so you don't need
#' # to explicitly add them.
#'
#' est_fe = feols(y ~ x1 | id + period, base_did)
#'
#' # Clustered along "id"
#' se(vcov(est_fe, "cluster"))
#'
#' # Clustered along "id" and "period"
#' se(vcov(est_fe, "twoway"))
#'
#'
#' # =========== #
#' # Panel VCOVs #
#' # =========== #
#'
#' # ---------------------|
#' # Newey West (NW) VCOV |
#' # ---------------------|
#' # To obtain NW VCOVs, use a formula of the form NW ~ id + period
#' se(vcov(est, NW ~ id + period))
#'
#' # If you want to change the lag:
#' se(vcov(est, NW(3) ~ id + period))
#'
#' # Alternative way:
#'
#' # -> using the vcov_NW function
#' se(vcov(est, vcov_NW(unit = "id", time = "period", lag = 3)))
#'
#' # -------------------------|
#' # Driscoll-Kraay (DK) VCOV |
#' # -------------------------|
#' # To obtain DK VCOVs, use a formula of the form DK ~ period
#'
#' se(vcov(est, DK ~ period))
#'
#' # If you want to change the lag:
#' se(vcov(est, DK(3) ~ period))
#'
#' # Alternative way:
#'
#' # -> using the vcov_DK function
#' se(vcov(est, vcov_DK(time = "period", lag = 3)))
#'
#' # -------------------|
#' # Implicit deduction |
#' # -------------------|
#' # When the estimation contains a panel identifier, you don't need
#' # to re-write them later on
#'
#' est_panel = feols(y ~ x1, base_did, panel.id = ~id + period)
#'
#' # Both methods, NM and DK, now work automatically
#' se(vcov(est_panel, "NW"))
#' se(vcov(est_panel, "DK"))
#'
#'
#' # =================================== #
#' # VCOVs robust to spatial correlation #
#' # =================================== #
#'
#' data(quakes)
#' est_geo = feols(depth ~ mag, quakes)
#'
#' # ------------|
#' # Conley VCOV |
#' # ------------|
#' # To obtain a Conley VCOV, use a formula of the form conley(cutoff) ~ lat + lon
#' # with lat/lon the latitude/longitude variable names in the data set
#' se(vcov(est_geo, conley(100) ~ lat + long))
#'
#' # Alternative way:
#'
#' # -> using the vcov_DK function
#' se(vcov(est_geo, vcov_conley(lat = "lat", lon = "long", cutoff = 100)))
#'
#' # -------------------|
#' # Implicit deduction |
#' # -------------------|
#' # By default the latitude and longitude are directly fetched in the data based
#' # on pattern matching. So you don't have to specify them.
#' # Furhter, an automatic cutoff is deduced by default.
#'
#' # The following works:
#' se(vcov(est_geo, "conley"))
#'
#'
#' # ======================== #
#' # Small Sample Corrections #
#' # ======================== #
#'
#' # You can change the way the small sample corrections are done with the argument ssc.
#' # The argument ssc must be created by the ssc function
#' se(vcov(est, ssc = ssc(adj = FALSE)))
#'
#' # You can add directly the call to ssc in the vcov formula.
#' # You need to add it like a variable:
#' se(vcov(est, iid ~ ssc(adj = FALSE)))
#' se(vcov(est, DK ~ period + ssc(adj = FALSE)))
#'
#'
#'
vcov.fixest = function(object, vcov = NULL, se = NULL, cluster, ssc = NULL, attr = FALSE,
forceCovariance = FALSE, keepBounded = FALSE,
nthreads = getFixest_nthreads(), vcov_fix = TRUE, ...){
# computes the clustered vcov
check_arg(attr, "logical scalar")
is_attr = attr
dots = list(...)
# START :: SECTION used only internally in fixest_env
only_varnames = isTRUE(dots$only_varnames)
data_names = dots$data_names
if(only_varnames){
# Used internally in fixest_env to find out which variable to keep
# => we need panel.id, so we can remove the NAs from it if it is implicitly deduced to be used
# => idem for fixef_vars
object = list(panel.id = dots$panel.id, fixef_vars = dots$fixef_vars)
}
# END
if(isTRUE(object$NA_model)){
# means that the estimation is done without any valid variable
return(object$cov.scaled)
}
if("dof" %in% names(dots)){
if(is.null(getOption("fixest_warn_dof_arg"))){
warning("The argument 'dof' is deprecated. Please use 'ssc' instead.")
options(fixest_warn_dof_arg = TRUE)
}
ssc = dots$dof
}
if(is_user_level_call()){
if(!is_function_in_it(vcov)){
validate_dots(suggest_args = c("vcov", "ssc"), valid_args = "dof")
}
}
# All the available VCOVs
all_vcov = getOption("fixest_vcov_builtin")
all_vcov_names = unlist(lapply(all_vcov, `[[`, "name"))
all_vcov_names = all_vcov_names[nchar(all_vcov_names) > 0]
# We transform se and cluster into vcov
vcov_vars = var_values_all = var_names_all = NULL
vcov = oldargs_to_vcov(se, cluster, vcov)
sandwich = !isFALSE(dots$sandwich) # I know it's weird
if(!is.null(object$onlyFixef)){
# means that the estimation is done without variables
return(NULL)
}
# If it's a summary => we give the vcov directly without further computation! except if arguments are provided which would mean that the user wants the new vcov
if(isTRUE(object$summary) && missnull(vcov) && missnull(ssc)){
vcov = object$cov.scaled
if(!is_attr) {
all_attr = names(attributes(vcov))
for(v in setdiff(all_attr, c("dim", "dimnames"))){
attr(vcov, v) = NULL
}
}
return(vcov)
}
# we inherit the vcov/ssc from the summary
assign_flags(object$summary_flags, vcov = vcov, ssc = ssc)
# Default behavior vcov:
suffix = ""
if(missnull(vcov)){
vcov_default = getFixest_vcov()
if(!is.null(object$panel.id)){
# Panel has precedence over FEs
vcov = vcov_default$panel
} else {
n_fe = length(object$fixef_id)
if(n_fe == 0){
vcov = vcov_default$no_FE
} else if(n_fe == 1){
vcov = vcov_default$one_FE
} else {
vcov = vcov_default$two_FE
}
if(!is.null(object$fixef_sizes) && object$fixef_sizes[1] == 1){
# Special case => cleaner output
vcov = vcov_default$no_FE
}
}
}
if(isTRUE(object$lean)){
# we can't compute the SE because scores are gone!
# LATER: recompute the scores (costly but maybe only possibility for user?)
#
# so only IID VCOV is valid
ok = FALSE
if(is.character(vcov) && length(vcov) == 1){
vcov_id = which(sapply(all_vcov, function(x) vcov %in% x$name))
if(length(vcov_id) == 1){
vcov_select = all_vcov[[vcov_id]]
ok = identical(vcov_select$vcov_label, "IID")
}
}
if(!ok) stop("VCOV of 'lean' fixest objects cannot be computed. Please re-estimate with 'lean = FALSE'.")
}
####
#### ... vcov parsing ####
####
# Checking the value of vcov
check_set_arg(vcov, "match | formula | function | matrix | list len(1) | class(fixest_vcov_request)", .choices = all_vcov_names)
user_vcov_name = NULL
if(is.list(vcov) && !inherits(vcov, "fixest_vcov_request")){
# We already ensured it was a list of length 1
user_vcov_name = names(vcov)
vcov = vcov[[1]]
}
if(is.function(vcov)){
if(only_varnames){
return(character(0))
}
# cleaning dots
for(var in c("summary_flags")){
dots[[var]] = NULL
}
# The name
arg_list = dots
if(".vcov_args" %in% names(dots)){
# internal call
vcov_name = dots$vcov_name
arg_list = dots$.vcov_args
} else {
vcov_name = attr(vcov, "deparsed_arg")
if(is.null(vcov_name)){
vcov_name = fetch_arg_deparse("vcov")
} else {
# cleaning
attr(vcov, "deparsed_arg") = NULL
}
# Getting the right arguments
arg_list = catch_fun_args(vcov, arg_list, exclude_args = "vcov", keep_dots = TRUE)
}
if(!is.null(user_vcov_name)){
vcov_name = user_vcov_name
} else {
vcov_name = gsub("sandwich::", "", vcov_name, fixed = TRUE)
vcov_name = gsub("^function\\([^\\)]+\\) ", "", vcov_name)
vcov_name = gsub("^vcov$", "Custom", vcov_name)
}
# We shouldn't have a prior on the name of the first argument
arg_names = formalArgs(vcov)
arg_list[[arg_names[1]]] = object
vcov = do.call(vcov, arg_list)
n_coef = length(object$coefficients)
check_value(vcov, "square numeric matrix nrow(value)", .value = n_coef,
.message = paste0("If argument 'vcov' is to be a function, it should return a square numeric matrix of the same dimension as the number of coefficients (here ", n_coef, ")."))
# We add the type of the matrix
attr(vcov, "type") = vcov_name
attr(vcov, "dof.K") = object$nparams
return(vcov)
}
if(is.matrix(vcov)){
if(only_varnames){
stop("A custom VCOV matrix cannot be used directly in a fixest estimation.")
}
# Check that this makes sense
n_coef = length(object$coefficients)
check_value(vcov, "square matrix nrow(value)", .value = n_coef)
attr(vcov, "type") = if(is.null(user_vcov_name)) "Custom" else user_vcov_name
attr(vcov, "dof.K") = object$nparams
return(vcov)
}
extra_args = NULL
if(inherits(vcov, "fixest_vcov_request")){
if(!is.null(vcov$ssc)) ssc = vcov$ssc
var_names_all = vcov$var_names_all
var_values_all = vcov$vcov_vars
extra_args = vcov$extra_args
vcov = vcov$vcov
}
if(inherits(vcov, "formula")){
vcov_fml = vcov
if(length(vcov_fml) == 2){
vcov = ""
vcov_vars = fml2varnames(vcov_fml, combine_fun = TRUE)
} else {
vcov = deparse_long(vcov_fml[[2]])
is_extra = grepl("(", vcov, fixed = TRUE)
if(is_extra){
vcov = trimws(gsub("\\(.+", "", vcov))
}
check_set_arg(vcov, "match",
.choices = all_vcov_names,
.message = "If a formula, the arg. 'vcov' must be of the form 'vcov_type ~ vars'. The vcov_type must be a supported VCOV type.")
if(is_extra){
new_req = eval(vcov_fml[[2]], environment(vcov_fml))
extra_args = new_req$extra_args
}
vcov_vars = fml2varnames(vcov_fml[c(1, 3)], combine_fun = TRUE)
}
qui_ssc = grepl("ssc(", vcov_vars, fixed = TRUE)
if(any(qui_ssc)){
ssc_txt = vcov_vars[qui_ssc]
ssc = eval(str2lang(ssc_txt))
vcov_vars = vcov_vars[!qui_ssc]
}
}
# Here vcov **must** be a character scalar
vcov_id = which(sapply(all_vcov, function(x) vcov %in% x$name))
if(length(vcov_id) != 1){
stop("Unexpected problem in the selection of the VCOV. This is an internal error. Could you report?")
}
vcov_select = all_vcov[[vcov_id]]
if(length(vcov_select$vars) == 0){
var_names_all = character(0)
if(only_varnames){
return(var_names_all)
}
} else {
if(!is.null(var_values_all)){
# If we're here, this means that vcov_vars
# has been provided via a vcov_request:
# - either via retro-compatibility (use of "cluster" with a vector or list)
# - either via feeding vectors into the user level version of the VCOV requested
#
# => so we don't have to do anything, checking will come later and is common with
# the else{} of this condition
is_int_all = list()
if(only_varnames){
return(character(0))
}
# We trim the observations if needed
for(i in seq_along(var_values_all)){
value = var_values_all[[i]]
if(length(value) != object$nobs_origin){
stopi("To compute the {vcov_select$vcov_label} VCOV, you need to provide variables with the same number of observations as in the original data set. Currently there are {len ? value} instead of {n ? object$nobs_origin}.")
}
var_values_all[[i]] = trim_obs_removed(value, object)
}
} else {
patterns_split = strsplit(vcov_select$patterns, " ?\\+ ?")
n_patterns = lengths(patterns_split)
if(isTRUE(object$is_fit)){
# No automatic deduction for fit methods,except for clustered SEs
n_FE = length(object$fixef_vars)
if(vcov_select$vcov_label %in% "Clustered"){
if(n_FE == 0){
stop("To compute a clustered VCOV from a '.fit' estimation, you need to provide the variables over which to cluster with the function vcov_cluster(). E.g. vcov = vcov_cluster(cluster = df) with df a data.frame containing the clusters. Or make a regular estimation, i.e. not from '.fit'.")
}
if(!n_FE %in% n_patterns){
stop("To compute a clustered VCOV from a '.fit' estimation, you need to provide the variables over which to cluster with the function vcov = vcov_cluster(cluster = df), with df a data.frmae containing the clusters. Or make a regular estimation, i.e. not from '.fit'.")
}
} else {
stop("The estimations from '.fit' methods don't support ", vcov_select$vcov_label, " VCOVs. To use them, perform a regular estimation instead.")
}
}
if(only_varnames == FALSE){
data = fetch_data(object)
data_names = names(data)
}
if(!length(vcov_vars) %in% n_patterns){
fml_display = paste0("~ ", vcov_select$patterns[n_patterns != 0])
stopi("In the argument 'vcov', the number of variables in the RHS of the formula ({len ? vcov_vars}) is not valid. The formula should correspond to{&n_patterns>1; one of} {enum.bq.or ? fml_display}.")
}
var_values_all = list()
# => list of variables used to compute the VCOV
var_names_all = c()
# => same as var_values_all but the variable names
is_int_all = list()
# => flag to avoid reapplying to_integer
pattern = patterns_split[[which(n_patterns == length(vcov_vars))]]
# We find all the variable names and then evaluate them
for(i in seq_along(vcov_select$vars)){
vcov_var_name = names(vcov_select$vars)[i]
vcov_var_value = vcov_select$vars[[i]]
if(vcov_var_name %in% pattern){
# => provided by the user, we find which one it corresponds to
# based on the pattern
vname = vcov_vars[which(pattern == vcov_var_name)]
vname_all = all.vars(str2expression(vname))
if(!all(vname_all %in% data_names)){
pblm = setdiff(vname_all, data_names)
stopi("The variable{$s, enum.q ? pblm}, used to compute the VCOV, {$are} not in the original data set. Only variables in the data set can be used.")
}
var_names_all[vcov_var_name] = rename_hat(vname)
if(only_varnames) {
var_names_all[vcov_var_name] = vname_all[1]
# To handle combined clusters
var_names_all = c(var_names_all, vname_all[-1])
next
}
value = eval(str2expression(vname), data)
var_values_all[[vcov_var_name]] = trim_obs_removed(value, object)
} else {
####
#### ... --- guessing the variables ####
####
# not provided by the user: GUESSED!
# 3 types of guesses:
# - fixef (fixed-effects used in the estimation)
# - panel.id (panel identifiers used in the estimation)
# - regex (based on variable names)
#
guesses = vcov_var_value$guess_from
# err_msg, vector of elements of the form c("expect" = "pblm")
err_msg = c()
for(k in seq_along(guesses)){
type = names(guesses)[k]
if(type == "fixef"){
if(is.null(object$fixef_vars)){
msg = setNames(nm = "the fixed-effects",
"there was no fixed-effect in the estimation")
err_msg = c(err_msg, msg)
next
}
if(length(object$fixef_vars) < guesses$fixef){
msg = setNames(nm = sma("the {nth ? guesses$fixef} fixed-effect"),
sma("the estimation had only {Len ? object$fixef_vars} ",
"fixed-effect{$s}"))
err_msg = c(err_msg, msg)
next
}
var_names_all[vcov_var_name] = object$fixef_vars[guesses$fixef]
if(only_varnames) break
is_int_all[[vcov_var_name]] = TRUE
var_values_all[[vcov_var_name]] = object$fixef_id[[guesses$fixef]]
break
} else if(type == "panel.id"){
if(is.null(object$panel.id)){
msg = setNames(nm = "the 'panel.id' identifiers",
"no 'panel.id' was set in this estimation")
err_msg = c(err_msg, msg)
next
}
vname = object$panel.id[guesses$panel.id]
vname_all = all.vars(str2expression(vname))
if(!all(vname_all %in% data_names)){
pblm = setdiff(vname_all, data_names)
msg = setNames(nm = "the 'panel.id' identifiers",
sma("the variable{$s ? pblm} set in 'panel.id' {$are} not in the data set"))
err_msg = c(err_msg, msg)
next
}
# ATTENTION:
# if the panel.id variable has NA values, and there are no lags used in the estimation
# (which would trigger obs removal), then we cannot use the panel.id
# for the VCOV reliably since the sample would differ from the sample used in the
# estimation
var_names_all[vcov_var_name] = vname
if(only_varnames) break
value = eval(str2expression(vname), data)
var_values_all[[vcov_var_name]] = trim_obs_removed(value, object)
break
} else if(type == "regex"){
ok = FALSE
msg = NULL
for(pat in guesses$regex){
var_id = which(grepl(pat, data_names))
if(length(var_id) == 0){
if(is.null(msg)){
msg = setNames(nm = "the variable names of the data set",
paste0("no match was found for ", vcov_var_value$label))
}
} else if(length(var_id) == 1){
ok = TRUE
vname = data_names[var_id]
break
} else {
msg = setNames(nm = "the variable names of the data set",
sma("several matches were found: {enum.i.q ? data_names[var_id]}"))
}
}
if(ok){
var_names_all[vcov_var_name] = vname
if(only_varnames) break
var_values_all[[vcov_var_name]] = trim_obs_removed(data[[vname]], object)
break
} else {
err_msg = c(err_msg, msg)
}
}
}
if(is.null(var_names_all[vcov_var_name]) &&
length(err_msg) > 0 && !isTRUE(vcov_var_value$optional)){
if(length(err_msg) == 1){
expect = names(err_msg)
pblm = err_msg
} else {
expect = enumerate_items(names(err_msg), "enum a.or")
pblm = enumerate_items(err_msg, "enum a")
}
stop("To compute the ", vcov_select$vcov_label, " VCOV, we need a variable for the ",
vcov_var_value$label, ". Since you didn't provide it in the formula, ",
"we typically deduce it from ", expect, ". ",
"PROBLEM: ", pblm, ". Please provide it in the formula.")
}
}
}
if(only_varnames){
return(var_names_all)
}
}
# Extra checking + putting into int if requested
for(i in seq_along(var_values_all)){
vcov_var_name = names(var_values_all)[i]
vname = var_names_all[vcov_var_name]
value = var_values_all[[i]]
vcov_var_value = vcov_select$vars[[vcov_var_name]]
if(!isTRUE(is_int_all[[vcov_var_name]]) && anyNA(value)){
# First condition means: it is a fixed-effect used in the estimation => no need to check
stop("The variable '", vname, "' used to estimate the VCOV (employed as ", vcov_var_value$label, ") has NA values which would lead to a sample used to compute the VCOV different from the sample used to estimate the parameters. This would lead to wrong inference.\nPossible solutions: i) ex ante prune them, ii) impute them, or iii) use the argument 'vcov' at estimation time.")
}
if(isTRUE(vcov_var_value$to_int)){
# if to_int => we do not have to check the type since it can be applied to any type
if(!isTRUE(is_int_all[[vcov_var_name]])){
var_values_all[[vcov_var_name]] = quickUnclassFactor(value)
}
} else if(!is.null(vcov_var_value$expected_type)){
check_value(value, .type = vcov_var_value$expected_type,
.prefix = paste0("To compute the VCOV, the ", vcov_var_value$label, " (here '", vname, "') "))
}
}
vcov_vars = var_values_all
}
# Checking the nber of threads
if(!missing(nthreads)) nthreads = check_set_nthreads(nthreads)
####
#### ... scores ####
####
# We handle the bounded parameters:
isBounded = object$isBounded
if(is.null(isBounded)){
isBounded = rep(FALSE, length(object$coefficients))
}
if(any(isBounded)){
if(keepBounded){
# we treat the bounded parameters as regular variables
scores = object$scores
object$cov.iid = solve(object$hessian)
} else {
scores = object$scores[, -which(isBounded), drop = FALSE]
}
} else {
scores = object$scores
}
####
#### ... bread ####
####
n = object$nobs
if(object$method_type == "feols"){
iid_names = all_vcov[[1]]$name
if(vcov %in% iid_names){
bread = object$cov.iid / ((n - 1) / (n - object$nparams))
} else {
bread = object$cov.iid / object$sigma2
}
} else {
bread = object$cov.iid
}
if(anyNA(bread)){
IS_NA_VCOV = FALSE
if(!forceCovariance){
IS_NA_VCOV = TRUE
} else {
info_inv = cpp_cholesky(object$hessian)
if(!is.null(info_inv$all_removed)){
# Means all variables are collinear! => can happen when using FEs
IS_NA_VCOV = TRUE
}
}
if(IS_NA_VCOV){
attr(bread, "type") = "NA (not-available)"
if(is_attr){
attr(bread, "dof.K") = object$nparams
attr(bread, "df.t") = NA
}
return(bread)
}
VCOV_raw_forced = info_inv$XtX_inv
if(any(info_inv$id_excl)){
n_collin = sum(info_inv$all_removed)
mema("NOTE: {N ? n_collin} variable{#s, have} been found to be singular.")
VCOV_raw_forced = cpp_mat_reconstruct(VCOV_raw_forced, info_inv$id_excl)
VCOV_raw_forced[, info_inv$id_excl] = NA
VCOV_raw_forced[info_inv$id_excl, ] = NA
}
bread = VCOV_raw_forced
}
####
#### ... vcov no adj ####
####
# we compute the vcov. The adjustment (which is a pain in the neck) will come after that
# Here vcov is ALWAYS a character scalar
# ssc related => we accept NULL
# we check ssc since it can be used by the funs
if(missnull(ssc)) ssc = getFixest_ssc()
check_arg(ssc, "class(ssc.type)",
.message = "The argument 'ssc' must be an object created by the function ssc().")
fun_name = vcov_select$fun_name
args = list(bread = bread, scores = scores, vars = vcov_vars, ssc = ssc,
sandwich = sandwich, nthreads = nthreads,
var_names_all = var_names_all)
for(a in names(extra_args)){
# I have to add this weird condition (because of the aliases)
if(!is.null(extra_args[[a]])) args[[a]] = extra_args[[a]]
}
vcov_noAdj = do.call(fun_name, args)
if(!sandwich){
return(vcov_noAdj)
}
dimnames(vcov_noAdj) = dimnames(bread)
####
#### ... ssc ####
####
# ssc is a ssc object in here
n_fe = n_fe_ok = length(object$fixef_id)
# we adjust the fixef sizes to account for slopes
fixef_sizes_ok = object$fixef_sizes
isSlope = FALSE
if(!is.null(object$fixef_terms)){
isSlope = TRUE
# The drop the fixef_sizes for only slopes
fixef_sizes_ok[object$slope_flag < 0] = 0
n_fe_ok = sum(fixef_sizes_ok > 0)
}
nested_vars = sapply(vcov_select$vars, function(x) isTRUE(x$rm_nested))
any_nested_var = length(nested_vars) > 0 && length(vcov_vars) > 0 && any(nested_vars[names(vcov_vars)])
if(ssc$fixef.K == "none"){
# we do it with "minus" because of only slopes
K = object$nparams
if(n_fe_ok > 0){
K = K - (sum(fixef_sizes_ok) - (n_fe_ok - 1))
}
} else if(ssc$fixef.K == "full" || !any_nested_var){
K = object$nparams
if(ssc$fixef.force_exact && n_fe >= 2 && n_fe_ok >= 1){
fe = fixef(object, notes = FALSE)
K = K + (n_fe_ok - 1) - sum(attr(fe, "references"))
}
} else {
# nested
# we delay the adjustment
K = object$nparams
}
#
# NESTING (== pain in the neck)
#
if(ssc$fixef.K == "nested" && n_fe_ok > 0 && any_nested_var){
# OK, let's go checking....
# We always try to minimize computation.
# So we maximize deduction and apply computation only in last resort.
nested_vcov_var_names = intersect(names(nested_vars[nested_vars]), names(vcov_vars))
nested_var_names = var_names_all[nested_vcov_var_names]
is_nested = rep(FALSE, n_fe)
for(i in 1:n_fe){
# We check for each FE
fe_name = object$fixef_vars[i]
if(fe_name %in% nested_var_names){
is_nested[i] = TRUE
next
} else if(grepl("^", fe_name, fixed = TRUE)){
# nesting of the FE in the parent term
fe_name_split = strsplit(fe_name, "^", fixed = TRUE)[[1]]
if(any(fe_name_split %in% nested_var_names)){
is_nested[i] = TRUE
next
}
}
}
# We check the remaining FEs, only if necessary
if(!all(is_nested) && !all(nested_var_names %in% object$fixef_vars)){
# Note that if all(nested_var_names %in% object$fixef_vars) == TRUE
# Then all the variables used to compute the VCOV are part of the FEs
# So the nesting would have been correctly spotted right before.
# Only caveat: if the user has a^b in FE and includes the parent terms (a and b), we may forget some nested FEs
# But then that's the user problem bc it's an erroneous specification
vcov_vars_nesting = vcov_vars[nested_vcov_var_names]
# We put the non integer to integer (needed)
id_to_int = which(sapply(vcov_select$vars[nested_vcov_var_names], function(x) !isTRUE(x$to_int)))
for(i in id_to_int){
vcov_vars_nesting[[i]] = quickUnclassFactor(vcov_vars_nesting[[i]])
}
id2check = which(is_nested == FALSE)
info = cpp_check_nested(object$fixef_id[id2check], vcov_vars_nesting,
object$fixef_sizes[id2check], n = n)
is_nested[id2check] = info == 1
}
if(sum(is_nested) == n_fe){
# All FEs are removed, we add 1 for the intercept
K = K - (sum(fixef_sizes_ok) - (n_fe_ok - 1)) + 1
} else {
if(ssc$fixef.force_exact && n_fe >= 2){
fe = fixef(object, notes = FALSE)
nb_ref = attr(fe, "references")
# Slopes are a pain in the neck!!!
if(sum(is_nested) > 1){
id_nested = intersect(names(nb_ref), names(object$fixef_id)[is_nested])
nb_ref[id_nested] = object$fixef_sizes[id_nested]
}
total_refs = sum(nb_ref)
K = K - total_refs
} else {
K = K - (sum(fixef_sizes_ok[is_nested]) - sum(fixef_sizes_ok[is_nested] > 0))
}
}
# below for consistency => should *not* be triggered
K = max(K, length(object$coefficients) + 1)
}
# Small sample adjustment
ss_adj = attr(vcov_noAdj, "ss_adj")
if(!is.null(ss_adj)){
if(is.function(ss_adj)){
ss_adj = ss_adj(n = n, K = K)
}
attr(vcov_noAdj, "ss_adj") = NULL
} else {
ss_adj = ifelse(ssc$adj, (n - 1) / (n - K), 1)
}
vcov_mat = vcov_noAdj * ss_adj
####
#### ... vcov attributes ####
####
if(any(diag(vcov_mat) < 0) && vcov_fix){
# We 'fix' it
all_attr = attributes(vcov_mat)
vcov_mat = mat_posdef_fix(vcov_mat)
is_complex = isTRUE(attr(vcov_mat, "is_complex"))