-
Notifications
You must be signed in to change notification settings - Fork 2
/
regress_utils.R
1915 lines (1811 loc) · 62.2 KB
/
regress_utils.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
#' Fully parse a formula for regress()
#' Takes in formula, potentially with nested F-tests
#'
#' @param form the formula to parse
#' @param modelframe the model frame which will become the model matrix. this ends up
#' being what is returned from match.call(), and so it looks like
#' regress(fnctl = "", formula = "", data = "", ...)
#' @param mat a vector containing the indices for matches between modelframe inputs and
#' c("formula", "data", "subset", "weights", "na.action", "offset") for lms, and
#' c("formula", "data", "subset", "weights", "na.action", "etastart", "mustart", "offset")
#' for glms
#' @param data the data frame
#'
#' @return a list of lists of tests to perform, the first of which will be the full model, named "overall"
#'
#' @keywords internal
#' @noRd
testList <- function(form, modelframe, mat, data){
# form[[3]] is the right-hand side of the formula
# tmplist should be null when only one predictor is present, unless specified inside a U() function
tmplist <- parsePartials(form[[3]], modelframe, mat) # should be null when only one predictor
charForm <- parseParseFormula(parseFormula(form[[3]], modelframe, mat))
# get unique variable names, and remove any "+"s since we'll add them in collapse below
charForm <- unique(charForm)
charForm <- charForm[charForm!= "+"]
charForm <- paste(deparse(form[[2]]), deparse(form[[1]]),paste(charForm, collapse="+"), sep="")
tmplist2 <- LinearizeNestedList(tmplist)
tmplist <- parseList(tmplist2)
forms <- getTerms(form, form[[2]])
forms <- parseList(LinearizeNestedList(forms))
names(forms) <- c("overall", names(tmplist))
if(length(tmplist)!=0){
form <- stats::as.formula(charForm, env=.GlobalEnv)
}
return(list(formula=form, testList=tmplist, termList = forms))
}
#' Function which takes in a string and returns a vector of individual characters
#' Helper function for print.uRegress
#'
#' @param str a string
#'
#' @return a vector of individual characters
#'
#' @keywords internal
#' @noRd
explode <- function(str){
chars <- strsplit(str, "")[[1]]
return (chars)
}
#' Takes a formula, returns a list of terms
#'
#' @param form the formula
#' @param y the dependent variable in a regression call, on the left hand side of the formula. This
#' is literally form[[2]] if it's from the same formula as what is entered into the \code{form} argument
#'
#' @return the list of terms
#'
#' @keywords internal
#' @noRd
getTerms <- function(form, y){
f1 <- as.list(form)
if(length(f1)==2){
if(storage.mode(form)=="symbol"){
return(NULL)
} else{
chars <- deparse(form)
if((grepl("U", f1[[1]]))){
if(grepl("=", chars, fixed=TRUE)){
chars <- unlist(strsplit(chars, "=", fixed=TRUE))
if(length(chars)>2){
chars <- c(chars[1], paste(chars[-1], collapse="="))
}
} else {
chars <- unlist(strsplit(chars, "(", fixed=TRUE))
}
chars[length(chars)] <- paste(unlist(strsplit(chars[length(chars)], ")", fixed=TRUE)), collapse=")")
chars <- paste(chars[-1], collapse="(")
chars <- paste(deparse(y), chars, sep="")
form <- stats::as.formula(chars, env=.GlobalEnv)
return(list(stats::terms(form), getTerms(f1[[2]], y)))
}
return(getTerms(f1[[2]], y))
}
} else if (length(f1)==1){
if(storage.mode(form)=="symbol"){
return(NULL)
} else{
return(NULL)
}
} else {
if(grepl("~", form[[1]], fixed=TRUE)){
ret <- stats::terms(form)
} else {
ret <- NULL
}
return(list(ret, lapply(f1, getTerms, form[[2]])))
}
}
#' Takes a formula, returns a viable formula
#'
#' @param form the formula
#' @param modelframe the modelframe
#' @param mat get indices for which parameters in mf correspond to certain parameters inside of \code{form}
#'
#' @return the list
#'
#' @keywords internal
#' @noRd
parseFormula <- function(form, modelframe, mat){
f1 <- as.list(form)
if (length(f1) == 1) {
return(form)
} else if (length(f1) == 2) {
if (sum(grepl("U", f1)) > 1) {
## if more than one U, need to evaluate nested U and then evaluate overall U
tmplistOne <- parsePartials(f1[[2]][[2]], modelframe, mat)
indx <- which(grepl("U", f1[[2]][[2]]))
for(i in indx){
char <- deparse(f1[[2]][[2]][[i]])
char2 <- unlist(strsplit(char, "~", fixed=TRUE))
if(sum(grepl("U", char2))>1){
char2 <- unlist(strsplit(char2, "U"))
## add on the appropriate parentheses
char2 <- unlist(strsplit(char2, "U"))
## take everything with no equals sign
char2 <- char2[!grepl("=", char2, fixed=TRUE)]
char2 <- paste(char2, collapse="(")
} else {
char2 <- char2[!grepl("U", char2)]
}
char2 <- paste("(", char2, sep="")
f1tmp <- stats::as.formula(paste("~", char2))
f1[[2]][[2]][[i]] <- f1tmp[[2]]
}
form[[2]] <- f1[[2]]
}
if (sum(grepl("U", f1)) == 1) {
## try to evaluate the formula
tmp <- tryCatch({eval(form, parent.frame())}, error=function(e){NULL})
if (!is.null(tmp)) {
tmpForList <- modelframe
tmpForList <- tmpForList[c(1L, mat)]
tmpForList$drop.unused.levels <- TRUE
nms <- names(tmp)
tmp <- tmp[[1]]
tmpForList$formula <- tmp
tmpForList[[1L]] <- quote(stats::model.frame)
tmpForList <- eval(tmpForList, parent.frame())
tmplist <- list(tmpForList)
if(grepl("~", nms)){
names(tmplist) <- paste("U(",as.character(tmp)[2],")",sep="")
} else {
names(tmplist) <- nms
}
formNew <- f1[[2]][[2]]
return(formNew)
} else {
return(form)
}
} else {
return(form)
}
} else {
return(lapply(form, parseFormula, modelframe, mat))
}
}
#' Go through a parseFactor and get the relevant formulas and partials
#'
#' @param lst a list returned by parseFactor
#'
#' @return a list with two components - the formula and a list of all of the matrices
#'
#' @keywords internal
#' @noRd
parseParseFormula <- function(lst){
tmp <- unlist(lst)
parsetmp <- sapply(tmp, deparse)
len <- floor(length(parsetmp)/2)
oper <- rev(parsetmp[1:len])
vec <- matrix(parsetmp[(len+1):length(parsetmp)], nrow=1)
ret <- insertVec(vec, oper, 2)
return(ret)
}
#' Inserts a vector into another vector
#'
#' @param x1 the original vector, which \code{x2} gets inserted into
#' @param x2 the new vector, which is inserted into \code{x1}
#' @param indx the index for where \code{x2} should be inserted into \code{x1}
#'
#' @return a vector
#'
#' @keywords internal
#' @noRd
insertVec <- function(x1, x2, indx){
if(length(x2)==1){
if(length(x1)==1){
return(c(x1,x2))
} else {
return(c(x1[1:indx-1], x2, x1[indx:length(x1)]))
}
} else {
tmp1 <- insertVec(x1, x2[1], indx)
tmp2 <- insertVec(tmp1, x2[-1], indx+2)
return(tmp2)
}
}
#' Taken from https://sites.google.com/site/akhilsbehl/geekspace/articles/r/linearize_nested_lists_in_r
#' Author: Akhil S Bhel
#'
#' Implements a recursive algorithm to linearize nested lists upto any
#' arbitrary level of nesting (limited by R's allowance for recursion-depth).
#' By linearization, it is meant to bring all list branches emanating from
#' any nth-nested trunk upto the top-level trunk s.t. the return value is a
#' simple non-nested list having all branches emanating from this top-level
#' branch.
#'
#' Since dataframes are essentially lists a boolean option is provided to
#' switch on/off the linearization of dataframes. This has been found
#' desirable in the author's experience.
#'
#' Also, one'd typically want to preserve names in the lists in a way as to
#' clearly denote the association of any list element to it's nth-level
#' history. As such we provide a clean and simple method of preserving names
#' information of list elements. The names at any level of nesting are
#' appended to the names of all preceding trunks using the `NameSep` option
#' string as the seperator. The default `/` has been chosen to mimic the unix
#' tradition of filesystem hierarchies. The default behavior works with
#' existing names at any n-th level trunk, if found; otherwise, coerces simple
#' numeric names corresponding to the position of a list element on the
#' nth-trunk. Note, however, that this naming pattern does not ensure unique
#' names for all elements in the resulting list. If the nested lists had
#' non-unique names in a trunk the same would be reflected in the final list.
#' Also, note that the function does not at all handle cases where `some`
#' names are missing and some are not.
#'
#' Clearly, preserving the n-level hierarchy of branches in the element names
#' may lead to names that are too long. Often, only the depth of a list
#' element may only be important. To deal with this possibility a boolean
#' option called `ForceNames` has been provided. ForceNames shall drop all
#' original names in the lists and coerce simple numeric names which simply
#' indicate the position of an element at the nth-level trunk as well as all
#' preceding trunk numbers.
#'
#' @param NList to do
#' @param LinearizeDataFrames to do
#' @param NameSep to do
#' @param ForceNames to do
#'
#' @return LinearList: Named list
#'
#' @keywords internal
#' @noRd
LinearizeNestedList <- function(NList, LinearizeDataFrames=FALSE,
NameSep="/", ForceNames=FALSE) {
# Sanity checks:
#
stopifnot(is.character(NameSep), length(NameSep) == 1)
stopifnot(is.logical(LinearizeDataFrames), length(LinearizeDataFrames) == 1)
stopifnot(is.logical(ForceNames), length(ForceNames) == 1)
if (! is.list(NList)) return(NList)
#
# If no names on the top-level list coerce names. Recursion shall handle
# naming at all levels.
#
if (is.null(names(NList)) | ForceNames == TRUE)
names(NList) <- as.character(1:length(NList))
#
# If simply a dataframe deal promptly.
#
if (is.data.frame(NList) & LinearizeDataFrames == FALSE)
return(NList)
if (is.data.frame(NList) & LinearizeDataFrames == TRUE)
return(as.list(NList))
#
# Book-keeping code to employ a while loop.
#
A <- 1
B <- length(NList)
#
# We use a while loop to deal with the fact that the length of the nested
# list grows dynamically in the process of linearization.
#
while (A <= B) {
Element <- NList[[A]]
EName <- names(NList)[A]
if (is.list(Element)) {
#
# Before and After to keep track of the status of the top-level trunk
# below and above the current element.
#
if (A == 1) {
Before <- NULL
} else {
Before <- NList[1:(A - 1)]
}
if (A == B) {
After <- NULL
} else {
After <- NList[(A + 1):B]
}
#
# Treat dataframes specially.
#
if (is.data.frame(Element)) {
if (LinearizeDataFrames == TRUE) {
#
# `Jump` takes care of how much the list shall grow in this step.
#
Jump <- length(Element)
NList[[A]] <- NULL
#
# Generate or coerce names as need be.
#
if (is.null(names(Element)) | ForceNames == TRUE)
names(Element) <- as.character(1:length(Element))
#
# Just throw back as list since dataframes have no nesting.
#
Element <- as.list(Element)
#
# Update names
#
names(Element) <- paste(EName, names(Element), sep=NameSep)
#
# Plug the branch back into the top-level trunk.
#
NList <- c(Before, Element, After)
}
Jump <- 1
} else {
NList[[A]] <- NULL
#
# Go recursive! :)
#
if (is.null(names(Element)) | ForceNames == TRUE)
names(Element) <- as.character(1:length(Element))
Element <- LinearizeNestedList(Element, LinearizeDataFrames,
NameSep, ForceNames)
names(Element) <- paste(EName, names(Element), sep=NameSep)
Jump <- length(Element)
NList <- c(Before, Element, After)
}
} else {
Jump <- 1
}
#
# Update book-keeping variables.
#
A <- A + Jump
B <- length(NList)
}
return(NList)
}
#' Takes in a linearized list, returns a list with only the non-null components
#'
#' @param lst
#'
#' @return a list with only the non-null components
#'
#' @keywords internal
#' @noRd
parseList <- function(lst){
indx <- !sapply(lst, is.null)
tmp <- lst[indx]
nms <- names(tmp)
nms <- sapply(nms, explode, simplify="array")
if(any(indx)){
#if nms is a list
if(is.list(nms)){
newnms <- lapply(nms, getindx)
indx2 <- lapply(newnms, which)
if(!any(sapply(newnms, any))){
len <- length(tmp)
nmtmp <- unlist(strsplit(names(tmp), "/"))
indx3 <- suppressWarnings(as.numeric(nmtmp))
if(any(is.na(indx3))){
for(i in 1:len){
nms[[i]] <- nmtmp[which(is.na(indx3))[i]]
}
} else {
for(i in 1:len){
nms[[i]] <- nmtmp[i+1]
}
}
} else {
for(i in 1:length(nms)){
nms[[i]] <- getnm(matrix(nms[[i]], ncol=1), indx2[[i]])
}
}
} else{
if(is.matrix(nms)){
newnms <- apply(nms, 2, getindx)
indx2 <- apply(newnms, 2, which)
} else {
newnms <- getindx(nms)
indx2 <- which(newnms)
}
if (length(indx2)==0){
len <- length(tmp)
nmtmp <- unlist(strsplit(names(tmp), "/"))
nms <- rep(NA, len)
for(i in 1:len){
nms[i] <- nmtmp[i*2]
}
} else if(inherits(indx2, "integer")){
nms <- getnm(nms, max(indx2))
} else if(dim(indx2)[2]==1) {
nms <- getnm(nms, max(indx2))
} else {
nms <- getnm(nms, indx2)
}
}
names(tmp) <- nms
}
return(tmp)
}
#' Used in parseList
#' @keywords internal
#' @noRd
getindx <- function(strlst){
return(sapply(strlst, function(x) x=="U"))
}
#' Used in parseList
#' @keywords internal
#' @noRd
getnm <- function(strmat, indx){
newmat <- paste(strmat[indx[1]:dim(strmat)[1],1], collapse="")
if(length(indx)>1){
for(i in 2:length(indx)){
newmat <- c(newmat, paste(strmat[indx[i]:dim(strmat)[1],i], collapse=""))
}
}
return(newmat)
}
#' Takes a formula, returns a list of models for multiple partial tests
#'
#' @param form the right-hand side of a formula
#' @param modelframe the model frame which will become the model matrix. this ends up
#' being what is returned from match.call(), and so it looks like
#' regress(fnctl = "", formula = "", data = "", ...)
#' @param mat a vector containing the indices for matches between modelframe inputs and
#' c("formula", "data", "subset", "weights", "na.action", "offset") for lms, and
#' c("formula", "data", "subset", "weights", "na.action", "etastart", "mustart", "offset")
#' for glms
#'
#' @return the list
#'
#' @keywords internal
#' @noRd
parsePartials <- function(form, modelframe, mat){
# separates the formula into a list of three
# the first item is '+', the second is the first p-1 coefficients, the third is the last p'th coefficient
f1 <- as.list(form)
# length(f1 == 1), this means there's only coefficient on the right-hand side of the formula
if (length(f1) == 1) {
return(NULL)
} else if (length(f1) == 2 & (as.character(f1[[1]]) == "U")) {
# if only a single variable is specified inside of U, return NULL
# if (length(unlist(strsplit(deparse(f1[[2]]), "\\+"))) == 1) {
# return(NULL)
# }
# length(f1) == 2 if a formula looks something like fev ~ as.integer(sex), or fev ~ U(sex),
# where the only coefficient listed is inside parentheses
tmplistOne <- NULL
# if more than one U, need to evaluate nested U and then evaluate overall U
# Note from Taylor - I'm not convinced this is doing what we want it do when there
# is more than one U and also additional variables in the model outside of the U's
if (sum(grepl("U", f1)) > 1) {
tmplistOne <- parsePartials(f1[[2]][[2]], modelframe, mat)
tmp <- LinearizeNestedList(tmplistOne)
tmplistOne <- parseList(tmp)
indx <- which(grepl("U", f1[[2]][[2]]))
for(i in indx){
char <- deparse(f1[[2]][[2]][[i]])
char2 <- unlist(strsplit(char, "~", fixed=TRUE))
if(sum(grepl("U", char2))>1){
char2 <- unlist(strsplit(char2, "U"))
## add on the appropriate parentheses
char2 <- unlist(strsplit(char2, "U"))
## take everything with no equals sign
char2 <- char2[!grepl("=", char2, fixed=TRUE)]
char2 <- paste(char2, collapse="(")
} else {
char2 <- char2[!grepl("U", char2)]
}
char2 <- paste("(", char2, sep="")
f1tmp <- stats::as.formula(paste("~", char2))
f1[[2]][[2]][[i]] <- f1tmp[[2]]
}
form[[2]] <- f1[[2]]
}
# if only one U is specified...
if (sum(grepl("U", f1)) == 1) {
## try to evaluate the formula
tmp <- tryCatch({eval(form, parent.frame())}, error=function(e){NULL})
if (!is.null(tmp)) {
tmpForList <- modelframe
tmpForList <- tmpForList[c(1L, mat)]
tmpForList$drop.unused.levels <- TRUE
nms <- names(tmp)
if(!is.null(tmplistOne)){
nms <- c(nms, names(tmplistOne))
}
tmp <- tmp[[1]]
tmpForList$formula <- tmp
tmpForList[[1L]] <- quote(stats::model.frame)
tmpForList <- eval(tmpForList, parent.frame())
tmplist <- list(tmpForList)
if(!is.null(tmplistOne)){
tmplist <- c(tmplist, tmplistOne)
}
if(any(grepl("~", nms))){
names(tmplist) <- paste("U(",as.character(tmp)[2],")",sep="")
} else {
names(tmplist) <- nms
}
return(tmplist)
} else {
return(NULL)
}
} else {
return(NULL)
}
} else {
return(lapply(form, parsePartials, modelframe, mat))
}
}
#' Create a Partial Formula
#'
#' Creates a partial formula of the form \code{~var1 + var2}. The partial formula can be named
#' by adding an equals sign before the tilde.
#'
#'
#' @param ... partial formula of the form \code{~var1 + var2}.
#' @return A partial formula (potentially named) for use in \code{\link[rigr]{regress}}.
#'
#' @seealso \code{\link[rigr]{regress}}
#' @examples
#'
#' # Reading in a dataset
#' data(mri)
#'
#' # Create a named partial formula
#' U(ma=~male+age)
#'
#' # Create an unnamed partial formula
#'
#' U(~male+age)
#'
#' @export U
U <- function(...) {
L <- list(...)
hypernames <- names(unlist(match.call(expand.dots=FALSE)$...))
names(L) <- unlist(match.call(expand.dots=FALSE)$...)
if(!is.null(hypernames)){
names(L) <- hypernames
}
return(L)
}
#' A function to traverse the termlist tree,
#' and create the correct augCoefficients matrix.
#' Helper function for regress()
#'
#' @param termlist the list with terms
#' @param mat the matrix to correct
#' @param ind a vector from 1:p, where p is the number of predictors in your model including the intercept
#'
#' @return A list with the updated augmented coefficients matrix and the current indices
#'
#' @keywords internal
#' @noRd
termTraverse <- function(termlist, mat, ind){
current <- termlist
lbls <- attr(current[[1]], "term.labels")
hasU <- grepl("U", lbls)
if(any(hasU)){
if(any(names(current)=="overall")){
return(termTraverse(termlist[-1], mat, ind))
} else {
tmp <- reFormat(termlist[1], lbls, mat, ind)
mat <- tmp$mat
# ind <- tmp$ind
return(termTraverse(termlist[-1], mat, ind))
}
} else if (length(termlist)>1){
t1 <- termTraverse(termlist[1], mat, ind)
m1 <- t1$mat
i1 <- t1$ind
return(termTraverse(termlist[-1], m1, i1))
} else {
#reformat goes here if needed
tmp <- reFormat(current, lbls, mat, ind)
mat <- tmp$mat
curIndx <- tmp$ind
return(list(mat=mat, ind=curIndx))
}
}
#' A function to check if all values in a vector are equal
#'
#' @param x a vector
#'
#' @return \code{TRUE}/\code{FALSE}
#'
#' @keywords internal
#' @noRd
equal <- function(x){
if(length(x)==1){
return(TRUE)
} else {
if(x[1]!=x[2]){
return(FALSE)
} else {
return(equal(x[-1]))
}
}
}
#' A helper function for termTraverse
#'
#' @param current the current terms
#' @param lbls the labels of the terms
#' @param mat the augmented coefficients matrix
#' @param ind the current indices
#'
#' @return A list with an updated augmented coefficients matrix and the current indices
#'
#' @keywords internal
#' @noRd
reFormat <- function(current, lbls, mat, ind){
include <- grepl(names(current), dimnames(mat)[[1]], fixed=TRUE)
includeHasInter <- grepl(":", dimnames(mat[include,])[[1]])
include[include][includeHasInter] <- FALSE
hasU <- grepl("U", lbls)
if(any(hasU)){
tmp <- lbls[hasU]
## only split if there is a name to the U
hasEq <- grepl("=", tmp, fixed=TRUE)
tmp2 <- tmp[hasEq]
tmp2 <- unlist(strsplit(tmp2, "U", fixed=TRUE))
if(sum(grepl(")", tmp2, fixed=TRUE))!=length(tmp2)-1){
tmp2 <- tmp2[-which(grepl(")", tmp2, fixed=TRUE))]
}
tmp2 <- as.matrix(tmp2)
tmp2 <- apply(tmp2, 1, splitOnParen)
hasEq2 <- grepl("=", tmp2, fixed=TRUE)
tmp2[hasEq2] <- unlist(lapply(strsplit(tmp2[hasEq2], "=", fixed=TRUE), function(x) return(x[1])))
tmp[hasEq] <- pasteTwo(tmp2)
lbls[hasU] <- tmp
lbls <- unlist(lapply(strsplit(lbls, " ", fixed=TRUE), function(x) return(x[1])))
}
rows <- sapply(lbls, grepl, dimnames(mat)[[1]], fixed=TRUE)
nestRows <- sapply(" ", grepl, dimnames(mat)[[1]], fixed=TRUE)
parenRows <- sapply("(", grepl, dimnames(mat)[[1]], fixed=TRUE)
nestRows[nestRows&parenRows] <- FALSE
## check if it is an interaction with the wrong thing
interRows <- sapply(":", grepl, dimnames(mat)[[1]], fixed=TRUE)
if(is.matrix(rows[interRows,])){
rows[interRows,] <- t(apply(rows[interRows,], 1, function(x) if(!equal(x)) return(rep(FALSE, length(x))) else return(x)))
}
## look at each column of rows. if nested are immediately after
## a row, put the nested in
rows <- apply(rows, 2, checkNesting, nestRows)
rows <- apply(rows, 1, sum)
rows <- ifelse(rows>=1, TRUE, FALSE)
indices <- which(rows)
indx <- max(which(include))
curIndx <- 1:length(ind)
bool <- !any(ind > curIndx)
if(bool){
dex <- NULL
} else {
dex <- min(which(ind>curIndx))
if(dex-1==1 & length(which(ind>curIndx))>1){
dex <- min(which(ind>curIndx)[-1])
}
}
if(bool){
if(min(indices)<indx){
curIndx <- c(1:(min(indices)-1), indx, indices, which(!rows))
} else {
curIndx <- c(1:indx, indices, which(!rows))
}
} else if (!any(interRows)){
if(max(indices)-min(indices)==1){
curIndx <- c(1:(min(indices[-1])-2), indx, indices, which(!rows))
} else {
curIndx <- c(1:(min(indices[-1])-1), indx, indices, which(!rows))
}
} else {
curIndx <- c(1:dex, indx, indices, which(!rows))
}
len <- max(which(curIndx==1))-1
tmpIndx <- curIndx[1:len]
if(length(tmpIndx)<length(ind)){
curIndx <- unique(curIndx)
} else if (tmpIndx[length(tmpIndx)]==ind[length(ind)]){
if(length(tmpIndx)-1 >= length(ind) & tmpIndx[length(tmpIndx)-1]!=ind[length(ind)-1]){
curIndx <- tmpIndx[-length(tmpIndx)]
} else {
curIndx <- unique(curIndx)
}
} else {
curIndx <- tmpIndx
}
mat <- mat[curIndx,]
return(list(mat=mat, ind=curIndx))
}
#' Function to paste every two elements in a vector together
#' Helper for termTraverse, regress
#'
#' @param vec the vector to paste together
#'
#' @return a vector with every two elements pasted together
#'
#' @keywords internal
#' @noRd
pasteTwo <- function(vec){
if(length(vec)==2){
return(paste(vec[1], vec[2], sep=""))
} else {
one <- pasteTwo(vec[1:2])
two <- pasteTwo(vec[-c(1:2)])
return(c(one, two))
}
}
#' Function to add the correct args onto a polynomial or dummy term
#' Used to live in pasting_args.R
#'
#' @param varname the variable name
#' @param var the variable itself
#' @param type a string, corresponding to either "polynomial" or "dummy"
#'
#' @return a list
#'
#' @keywords internal
#' @noRd
addArgs <- function(varname, var, type){
findx <- pmatch(type, c("polynomial", "dummy"))
type <- c("polynomial", "dummy")[findx]
att <- attributes(var)
args <- att$transformation
if(type=="polynomial"){
args <- list(transformation=args, degree=max(att$degree), center=att$center, nm=att$prnm, param=att$transformation)
varname <- unlist(strsplit(varname, "(", fixed=TRUE))[2]
varname <- unlist(strsplit(varname, ")", fixed=TRUE))[1]
varname <- unlist(strsplit(varname, ",", fixed=TRUE))[1]
varnames <- rev(pasteOn(rep(varname, args$degree), "^", args$degree))
} else {
args <-list(transformation=args, reference=min(att$reference_name), num=length(att$reference)-1, nm=att$prnm, param=att$transformation)
varname <- unlist(strsplit(varname, "(", fixed=TRUE))[2]
varname <- unlist(strsplit(varname, ")", fixed=TRUE))[1]
varname <- unlist(strsplit(varname, ",", fixed=TRUE))[1]
if (is.numeric(args$reference)) {
varnames <- rev(pasteOn(rep(varname, att$dim[2]), ".", att$dim[2]+args$reference))
} else {
varnames <- paste0(varname, ".", att$groups)
}
}
return(list(varnames, args))
}
#' Function to paste on degree
#' Used to live in pasting_args.R
#'
#' @param x the original vector
#' @param str what to paste onto the original vector (after)
#' @param num the numbers to add to the end of the original vector
#'
#' @return a vector of strings
#'
#' @keywords internal
#' @noRd
pasteOn <- function(x, str, num){
if(length(x)==1){
return(paste(x, str, num, sep=""))
} else{
ret <- paste(x[1], str, num, sep="")
ret2 <- pasteOn(x[-1], str, num-1)
return(c(ret, ret2))
}
}
#' Function that takes a pair and pastes together, with colon
#' Used to live in pasting_args.R
#'
#' @param vec
#'
#' @return a vector
#'
#' @keywords internal
#' @noRd
pastePair <- function(vec){
if(length(vec)==2){
return(paste(vec[1], ":", vec[2], sep=""))
} else{
ret1 <- paste(vec[1], ":", vec[2], sep="")
ret2 <- pastePair(vec[-c(1,2)])
return(c(ret1, ret2))
}
}
#' Function that sums across a logical vector, returns the current value at each point
#' Used to live in pasting_args.R
#'
#' @param vec a vector of integers
#'
#' @return a vector
#'
#' @keywords internal
#' @noRd
movingSum <- function(vec){
s <- rep(0, length(vec))
for(i in 1:length(vec)){
if(vec[i]){
s[i] <- i
} else {
s[i] <- 0
}
}
return(s)
}
#' Used to live in pasting_args.R
#'
#' @param num an index
#' @param vec a vector of integers (indices)
#'
#' @return a vector
#'
#' @keywords internal
#' @noRd
myNext <- function(num, vec){
if(which(vec==num)+1<= length(vec)){
ret <- vec[which(vec==num)+1]
} else {
ret <- which(vec==num)+1
}
return(ret)
}
#' Function to tack on args and return appropriate names for printing
#' Used to live in pasting_args.R
#'
#' @param p preds
#' @param h hyperpreds
#' @param mf model frame
#'
#'
#' @keywords internal
#' @noRd
reFormatReg <- function(p, h, mf){
polynomial <- grepl("polynomial\\(", h)
dummy <- grepl("dummy\\(", h)
args <- as.list(h)
parens <- grepl(")", p, fixed=TRUE)
interact <- grepl(":", p, fixed=TRUE)
indices <- dummy | polynomial
indices <- movingSum(indices)
indices <- indices[indices>0]
indx <- indices[1]
#cols <- preds ## fix cols in loops
if(any(polynomial)){
tmp <- h[polynomial]
for(i in 1:length(tmp)){
tmp2 <- addArgs(tmp[i], mf[,tmp[i]], type="poly")
args[[indx]] <- tmp2[[2]]
nms <- tmp2[[1]]
## get the correct naming
current <- p[grepl(tmp[i], p, fixed=TRUE)]
split <- unlist(strsplit(current, ":", fixed=TRUE))
bool <- length(current)==length(split)
repsplit <- split[grepl(tmp[i], split, fixed=TRUE)]
even <- FALSE
if(length(grepl(tmp[i], split, fixed=TRUE))>=3){
if(grepl(tmp[i], split, fixed=TRUE)[3]){
even <- FALSE
} else {
even <- TRUE
}
}
if(!even){
repsplit <- rep(nms, length(repsplit)/(args[[indx]]$degree))
} else {
len <- length(repsplit)/(args[[indx]]$degree)-1
repsplit <- rep(nms, 1)
for(j in 1:length(nms)){
repsplit <- c(repsplit, rep(nms[j], len))
}
}
split[grepl(tmp[i], split, fixed=TRUE)] <- repsplit
## paste back in, if interactions
if(!bool){
split[(args[[indx]]$degree+1):length(split)] <- pastePair(split[(args[[indx]]$degree+1):length(split)])
split <- unique(split)
current <- split
} else {
current <- split
}
p[grepl(tmp[i], p, fixed=TRUE)] <- current
indx <- myNext(indx, indices)
}
}
if(any(dummy)){
tmp <- h[dummy]
for(i in 1:length(tmp)){
tmp2 <- addArgs(tmp[i], mf[,tmp[i]], type="dum")
args[[indx]] <- tmp2[[2]]
nms <- tmp2[[1]]
## get the correct naming
current <- p[grepl(tmp[i], p, fixed=TRUE)]
split <- unlist(strsplit(current, ":", fixed=TRUE))
bool <- length(current)==length(split)
repsplit <- split[grepl(tmp[i], split, fixed=TRUE)]
even <- FALSE
if(length(grepl(tmp[i], split, fixed=TRUE))>=3){
if(grepl(tmp[i], split, fixed=TRUE)[3]){
even <- FALSE
} else {
even <- TRUE
}
}
if(!even){
repsplit <- rep(nms, length(repsplit)/(args[[indx]]$num))
} else {
len <- length(repsplit)/(args[[indx]]$num)-1
repsplit <- rep(nms, 1)
for(j in 1:length(nms)){
repsplit <- c(repsplit, rep(nms[j], len))
}
}
# Note from Taylor: this throws a warning, but the results seem to end up okay
# This is a temporary fix, and should be addressed in the future
# Note from Yiqun: something weird is happening here -- the default reference
# group is always preserved even in presence of ref="" argument; we are gonna
# take it out for now -- looks like it's replacing the wrong coef names
# Yiqun: this should fix the wrong labeling by removing the base categories
# in each iteration; interactions will have to be investigated further.
baseline_category <- paste0(args[[indx]]$nm,'.',args[[indx]]$reference)
repsplit <- repsplit[repsplit!=baseline_category] # ad hoc??
suppressWarnings(split[grepl(tmp[i], split, fixed=TRUE)] <- repsplit)
## paste back in, if interactions
if(!bool){
split[(args[[indx]]$num+1):length(split)] <- pastePair(split[(args[[indx]]$num+1):length(split)])
split <- unique(split)
current <- split
} else {
current <- split
}
p[grepl(tmp[i], p, fixed=TRUE)] <- current
indx <- myNext(indx, indices)
}
}
return(list(preds=p, args=args))
}
#' Function to create the correct columns for processTerm
#' Takes a predictor and the terms vector, determines which it is,
#' if an interaction, checks both
#' don't put in the intercept
#' Used to live in pasting_args.R
#'
#' @param pds predictor