-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulation script.R
More file actions
2265 lines (2141 loc) · 83.2 KB
/
Copy pathSimulation script.R
File metadata and controls
2265 lines (2141 loc) · 83.2 KB
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
################################################################################
##this code allows to perform a simulation to assess performance in terms of
##stability, sensitivity and specificity of prespecified statistical methods
##used to find the true predictors of an health among the exposome it contains 5
##parts:
##1. defining the functions allowing to generate a realistic dataset of exposome
#and an outcome linearly related to some variables of this exposome.
#It needs a real exposome dataset as input, as well as parameters allowing to
#define the #association between the exposome and the outcome (number of
#predictors, #variability explained, correlation..)
##2. defining the methods assessed
##3. defining some functions used to assess methods performance
##4. defining the simulation function, which, for a given scenario, generates
##the datasets, applies the methods and assess their performance. This function
##allows to parallelize the simulation.
##5. runnning the simulation itself with parallelization, repeating X times the
##function defined in 4. for each scenario and saving the results.
################################################################################
library(mvtnorm)
library(boot)
library(parallel)
library(reshape)
library(glmnet)
library(DSA)
library(OmicsMarkeR)
library(Rcpp)
library(stringr)
###########################################################
######### 1. Generating datasets - functions ##############
###########################################################
##Define functions used to generate datasets function which generates a
##dataset of exposures with same number of variables and individuals and similar
##correlation structure than a real exposome matrix provided and an outcome
##linearly generated
simulator_2layers <- function(E_true,
#real exposome data
R2_tot = 0.1 ,
#total variability explained all predictors
n_Ey = 5,
#number of predictors
BetaEy = 0.01,
#Beta coefficient for each predictors. Can be a
#vector of values or a unique value
test_and_training = TRUE,
#generate a dataset of the same size of E_true (if
#FALSE) or double the number of individuals (if
#TRUE)
pos_and_neg = FALSE,
#if FALSE, all effects are positive; if TRUE, half
#are negative
corr = F,
#if TRUE, the correlation between the predictors
#is controled
range_corr = c(0, 1)) {
#if corr = TRUE, range of correlation for true
#predictors
##creating a new exposome dataset by bootstraping
data.X <- as.data.frame(E_true)
names_row <- rownames(data.X)
data.X <- data.X[sample(1:nrow(data.X), 2 * nrow(data.X), replace = TRUE),]
rownames(data.X) <- c(names_row, sprintf('boot%s', names_row))
dataExp <- data.X
remove(data.X)
##creating a linearly generated outcome
##defining the vector of Beta coefficients
if (length(BetaEy) == 1) {
if (pos_and_neg == FALSE) {
Betapred_yE <- rep(BetaEy, n_Ey)
} else{
Betapred_yE <- rep(BetaEy, round(n_Ey / 2))
Betapred_yE <- c(Betapred_yE, rep(-BetaEy, n_Ey - length(Betapred_yE)))
}
} else{
if (length(BetaEy) != n_Ey) {
stop(
"error: Betas for M explaining Y not explained by E are not
consistent with the number of predictors"
)
}
Betapred_yE <- BetaEy
}
##creating the linear combination
yE <- simResponseSimple(
met = dataExp,
Nmet = n_Ey,
beta = Betapred_yE,
corr = corr,
range_corr = range_corr
)
##adding a gaussian to Y to reach the wanted level of variability explained by
##the linear combination of predictors
Y <- yE$resp
if (!is.na(R2_tot)) {
if (((R2_tot) != 0)) {
sigma <- var(Y) * (1 / R2_tot - 1)
} else{
R2 = 0.00000001
sigma <- var(Y) * (1 / R2_tot - 1)
}
Y <-
as.matrix(Y + rnorm(length(Y), mean(Y), sqrt(sigma)), ncol = 1)
Y <- as.data.frame(Y)
}
##estimating the R2
R2 <- estimatedR2(dataExp, yE$predictors, Y)$r.squared
##results to return
resultats <- list(
Y_train = Y[1:(nrow(dataExp) / 2), , drop = FALSE],
##train part of the generated Y vector
E_train = dataExp[1:(nrow(dataExp) / 2), , drop = FALSE],
##train part of the generated exposome dataset
Y_test = Y[(nrow(dataExp) / 2):nrow(dataExp), , drop =
FALSE],
##test part of the generated Y vector
E_test = dataExp[(nrow(dataExp) / 2):nrow(dataExp), , drop = FALSE],
##test part of the generated exposome dataset
yE = yE,
##yE (output of the simResponseSimple) object containing the list of
##predictors and the Betas
R2 = R2,
##estimated R2
list_predictor = as.character(yE$predictors) ##vectors of predictors
)
return(resultats)
}
####function to generate a linear response####
simResponseSimple <-function(met,
##dataframe of potential predictors
Nmet = NA,
##number of predictors
beta = NULL,
##Betas coefficient for predictors. Can be a vector of values or a
##unique value
cpg = NULL,
##name of forced predictors if necessary
corr = FALSE,
#if TRUE, the correlation between the predictors is controled
range_corr = c(0, 1)) {
#if corr = TRUE, range of correlation for true predictors
if (all(c(is.na(Nmet), is.null(cpg))) == TRUE) {
##case with no link between the response and the dataset of potential
##predictors
return (list(
resp = as.matrix(rep(0, nrow(met)), ncol = 1),
beta = NA,
predictors = NA
))
}
if (corr == FALSE | Nmet == 1) {
##case of only 1 predictors and no correlation cotnrol
temp <- Nmet - length(cpg)
if (temp != 0) {
if (length(cpg) == 0) {
wh <- sample((1:ncol(met)), temp) ##drawing predictors
} else{
##drawing predictors while conserving those specified if some were
##specified as input
wh <- sample((1:ncol(met)[-cpg]), temp)
wh <- c(cpg, wh)
}
} else{
wh <- cpg
}
} else{
if (length(cpg) != 0) {
stop("set corr to true is only possible when names of predictors
are not provided")
}
##if a specified correlation between predictors is set by the users,
##selecting the predictors to be in this specified range
wh <- submatFindSimpl(Mat <- as.matrix(met), range = range_corr, Nvar = Nmet)
wh <- which(colnames(met) %in% wh)
}
##defining a matrix of predictors
CovMat <- as.matrix(met[, wh])
colnames(CovMat) <- colnames(met)[wh]
# computing the response
mean <- CovMat %*% matrix(beta, ncol = 1)
rownames(mean) <- rownames(met)
names(beta) <- colnames(CovMat)
return (list(
resp = mean,
##response vector
beta = beta,
##Betas coefficient vector
predictors = colnames(CovMat) ##vector of predictors
))
}
####function to choose a set of predictors among a set of variables with a
####constraint on the correlation range between predictors####
submatFindSimpl <- function(Mat, range = c(0, 1), Nvar) {
# verifying formats and values of inputs
if (Nvar > ncol(Mat))
stop("No matrix of the correct size meeting the range criterion")
if (Nvar < 2)
stop("Nvar must be at least 2")
# computing the correlation matrix
Mat <- abs(cor(Mat))
diag(Mat) <- NA
# removing rows with no correlation value in the given range
wh <- which(apply(Mat, 1, min, na.rm = T) > range[2] |
apply(Mat, 1, max, na.rm = T) < range[1])
if (length(wh) > 0)
Mat <- Mat[-wh, -wh]
# iteratively selecting and testing samples for the correct correlation
Res <- NA
samp1 <- sample(1:ncol(Mat), size = ncol(Mat))
t1 <- 1
while (t1 <= ncol(Mat) & all(is.na(Res))) {
var <- array(NA, 0)
t2 <- samp1[t1]
while (all(is.na(Res)) & length(t2) > 0) {
if (length(t2) == 1) var <- c(var, t2)
if (length(t2) > 1) var <- c(var, sample(t2, size = 1))
t2 <- (1:ncol(Mat))[-var]
if (length(t2) > 1)
t2 <- t2[which(apply(as.matrix(Mat[t2, var] <= range[2] &
Mat[t2, var] >= range[1] &
Mat[t2, var] < 1), 1, min) == 1)]
if (length(t2) == 1){
if (min(c(Mat[t2, var] <= range[2], Mat[t2, var] >= range[1],
Mat[t2, var] < 1)) != 1)
t2 <- NA
}
if (length(var) == Nvar)
Res <- var
}
t1 <- t1 + 1
}
if (all(is.na(Res)))
stop("Not enough variable with the given correlation range")
return(colnames(Mat)[Res])
}
####function which estimates R2 from a dataset of potential predictors, the list
####of true predictors and a vector of outcome####
estimatedR2 <- function(X, truepred, Y) {
if ("y" %in% truepred) {
stop("error: one of the true predictors is named y")
}
if (ncol(Y) != 1) {
stop("error:Y is multidimensionnal")
}
if (nrow(X) != nrow(Y)) {
stop("error: not the same number of rows")
}
if (isTRUE(all.equal(rownames(X), rownames(Y))) == FALSE) {
stop("error: individuals are not ordered similarly in X and Y")
}
if (all(truepred %in% colnames(X))) {
data <- X[, colnames(X) %in% truepred, drop = FALSE]
data <- cbind(Y, data)
colnames(data)[1] <- "y"
mod <- lm(y ~ ., as.data.frame(data))
toselect.x <- summary(mod)$coeff[-1, 4]
r <- list(summary(mod)$r.squared,
summary(mod)$adj.r.squared,
names(toselect.x)[toselect.x == TRUE])
names(r) <- c("r.squared", "adj.r.squared", "pred")
return(r)
} else{
stop("error: X does not countain all true predictors")
}
}
################################################################################
##an other function simulator_2layers can be used if one want to control the
##correlation of the overall dataset in this case, the simulated exposome matrix
##is no longer obtained by bootstrapping the real exposome but from a
##correlation matrix the correlation matrix must be provided by the user or
##specified as nulll uncomment the section below and adapt the input of
##functions f0 (section 4.) and clusterApply (section 5.) to use it
# simulator_2layers <-
# function(names_rows_true,
# cormat,
# R2_tot = 0.1 ,
# n_Ey = 5,
# BetaEy = 0.01,
# test_and_training = TRUE,
# pos_and_neg = FALSE,
# corr_all = "real",
# corr_pred = TRUE,
# range_corr = c(0, 1)) {
# ##generation of exposome dataset DIFFERENT FROM THE OTHER FUNCTION
# simulator_2layers
# if (corr_all == "real") {
# data.X <- data.frame(rmvnorm(1173 * 2, rep(0, ncol(cormat)),
# cormat))
# } else{
# if (corr_all == "null") {
# cormat2 <- diag(ncol(cormat))
# data.X <- data.frame(rmvnorm(1173 * 2, rep(0, ncol(cormat)),
# cormat2))
# } else{
# stop("Correlation for the whole exposome (null or real) must
# be specifed")
# }
# }
# colnames(data.X) <- colnames(cormat)
# rownames(data.X) <-
# c(names_rows_true, sprintf('boot%s', (names_rows_true)))
# dataExp <- data.X
# remove(data.X)
#
# ##FROM HERE, THE FUNCTION IS IDENTICAL TO THE OTHER simulator_2layers
# function ##creating a linearly generated outcome ##defining the vector of
# Beta coefficients
#
# if (length(BetaEy) == 1) {
# if (pos_and_neg == FALSE) {
# Betapred_yE <- rep(BetaEy, n_Ey)
# } else{
# Betapred_yE <- rep(BetaEy, round(n_Ey / 2))
# Betapred_yE <-
# c(Betapred_yE, rep(-BetaEy, n_Ey - length(Betapred_yE)))
# }
# } else{
# if (length(BetaEy) != n_Ey) {
# stop(
# "error: Betas for M explaining Y not explained by E are not
# consistent with the number of predictors"
# )
# }
# Betapred_yE <- BetaEy
# }
# ##creating the linear combination
# yE <-
# simResponseSimple(
# met = dataExp,
# Nmet = n_Ey,
# beta = Betapred_yE,
# corr = corr,
# range_corr = range_corr
# )
#
# ##adding a gaussian to Y to reach the wanted level of variability
# explained by the linear combination of predictors
# Y <- yE$resp
# if (!is.na(R2_tot)) {
# if (((R2_tot) != 0)) {
# sigma <- var(Y) * (1 / R2_tot - 1)
# } else{
# R2 = 0.00000001
# sigma <- var(Y) * (1 / R2_tot - 1)
# }
# Y <-
# as.matrix(Y + rnorm(length(Y), mean(Y), sqrt(sigma)), ncol = 1)
# Y <- as.data.frame(Y)
# }
#
# ##estimating the R2
# R2 <- estimatedR2(dataExp, yE$predictors, Y)$r.squared
# ##results to return
# resultats <-
# list(
# Y_train = Y[1:(nrow(dataExp) / 2), , drop = FALSE],
# ##train part of the generated Y vector
# E_train = dataExp[1:(nrow(dataExp) / 2), , drop = FALSE],
# ##train part of the generated exposome dataset
# Y_test = Y[(nrow(dataExp) / 2):nrow(dataExp), , drop =
# FALSE],
# ##test part of the generated Y vector
# E_test = dataExp[(nrow(dataExp) / 2):nrow(dataExp), , drop = FALSE],
# ##test part of the generated exposome dataset
# yE = yE,
# ##yE (output of the simResponseSimple) object containing the list of
# ##predictors and the Betas
# R2 = R2,
# ##estimated R2
# list_predictor = as.character(yE$predictors) ##vectors of predictors
# )
# return(resultats)
# }
###########################################################
########### 2. Methods to be tested - functions ###########
###########################################################
####a function used to compute residuals from a linear model if covariates are
####part of the inputs of any the function of the methods tested####
getresiduals_2df <-
function(data_Y_in, data_covar_in, name_Y, covar) {
data_covar <-
data_covar_in[, colnames(data_covar_in) %in% covar, drop = FALSE]
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_covar),
colnames(data_Y_in) ==
name_Y, drop = FALSE]
data_covar <-
data_covar[rownames(data_covar) %in% rownames(data_Y), , drop = FALSE]
data_covar <- data_covar[rownames(data_Y), , drop = FALSE]
data_output <- data_Y
data <- cbind(data_Y, data_covar)
mod <- lm(data = data)
data_output[, 1] <- as.data.frame(residuals(mod))
return(data_output)
}
####ExWAS####
ewas <-
function(data_Xs_in,
##dataset of explanatory variables ("exposures")
data_Y_in,
##dataset of univariate variable of interest ("outcome")
name_Y,
##variable of interest name
data_covar_in = NULL,
##if neccessary, dataset of covariates ("confounders")
covar = character(0),
##if necessary, vector of covariates name
corr = "BY",
##name of multiple testing correction to be applied ("BH" or "Bon" or
##"BY" or "None")
ntest = NULL) {
##if ntest is a numeric, correction of multiple testing will be a Bonferroni
##correction considering ntest as the number of tests performed
require(parallel)
if (length(covar) > 0) {
##if necessary, computing residuals of the linear model explaining the
##variable of interest by the covariates
data_covar<-data_covar_in[rownames(data_covar_in) %in% rownames(data_Y_in) &
rownames(data_covar_in) %in% rownames(data_Xs_in),
colnames(data_covar_in) %in% covar, drop = FALSE]
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_covar) &
rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop =
FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_covar) &
rownames(data_Xs_in) %in% rownames(data_Y), , drop = FALSE]
data_covar <- data_covar[rownames(data_Y), , drop = FALSE]
data_Xs <- data_Xs[rownames(data_Y), , drop = FALSE]
data_Y <- getresiduals_2df(data_Y, data_covar, name_Y, covar)
} else{
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) ==
name_Y, drop = FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_Y_in),
, drop = FALSE]
data_Xs <- as.data.frame(data_Xs[rownames(data_Y), ])
colnames(data_Xs) <- colnames(data_Xs_in)
}
##checking consistency of the datasets
if (is.null(data_Y) == TRUE |
is.null(data_Xs) == TRUE |
!(name_Y %in% colnames(data_Y))) {
stop("Données incohérentes entre elles")
}
##applying univariate regression for each exposure outcome association
p.values <- mclapply(1:ncol(data_Xs), function(x, data_Xs) {
c(colnames(data_Xs)[x], summary(lm(Y ~ .,
data = data.frame(
cbind(var1 = data_Xs[, x],
Y = data_Y[, 1])
)))$coefficients[2, ])
},
data_Xs)
if (length(p.values) == 1) {
p.values <-
as.matrix(as.vector(unlist(p.values[[1]])), ncol = 5, byrow = TRUE)[-4, ]
p.values <- t(as.data.frame(p.values))
} else{
p.values <-
cbind(matrix(unlist(p.values), ncol = 5, byrow = TRUE)[, -4])
}
p.values <- as.data.frame(p.values)
colnames(p.values) <- c("var", "Est", "Sd", "pVal")
p.values <- p.values[p.values$var != "Intercept", ]
p.values$pVal <- as.numeric(as.character(p.values$pVal))
p.values.adj <- p.values
pVal <- as.numeric(as.character(p.values$pVal))
##applying correction for multiple testing
if (corr == "None") {
wh <- which(pVal <= 0.05)
p.values.adj$pVal_adj <- pVal
}
if (corr == "Bon") {
wh <- which(pVal <= 0.05 / nrow(p.values))
p.values.adj$pVal_adj <- pVal * nrow(p.values)
}
if (corr == "BH") {
wh <- which(p.adjust(pVal, "BH") <= 0.05)
p.values.adj$pVal_adj <- p.adjust(pVal, "BH")
}
if (corr == "BY") {
wh <- which(p.adjust(pVal, "BY") <= 0.05)
p.values.adj$pVal_adj <- p.adjust(pVal, "BY")
}
if (!corr %in% c("Bon", "BH", "BY", "", "None"))
stop("Please specify a known correction method for
multiple testing")
if (!is.null(ntest)) {
p.values.adj$pVal_adj <- pVal * ntest
}
wh_num <- wh
wh <- p.values$var[wh]
a <- list(wh, wh_num, p.values.adj)
##returning selected exposures and pvalues
names(a) <- c("selected", "indices_selected", "pval")
return(a)
}
####lasso - basic implementation#### this includes a basic 10-fold cross
##validation process as implemented in the CVglmnet package
lasso <-
function(data_Xs_in,
##dataset of explanatory variables ("exposures")
data_Y_in,
##dataset of univariate variable of interest ("outcome")
name_Y,
##variable of interest name
data_covar_in = NULL,
##if neccessary, dataset of covariates ("confounders")
covar = character(0)) {
##if necessary, vector of covariates name
if (length(covar) > 0) {
##if necessary, computing residuals of the linear model explaining the
##variable of interest by the covariates
data_covar <-
data_covar_in[rownames(data_covar_in) %in% rownames(data_Y_in) &
rownames(data_covar_in) %in% rownames(data_Xs_in),
colnames(data_covar_in) %in%
covar, drop = FALSE]
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_covar) &
rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop =
FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_covar) &
rownames(data_Xs_in) %in% rownames(data_Y_in),
, drop = FALSE]
data_covar <- data_covar[rownames(data_Y), ]
data_Xs <- data_Xs[rownames(data_Y), ]
data_Y <- getresiduals_2df(data_Y, data_covar, name_Y, covar)
} else{
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop = FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_Y_in), , drop = FALSE]
data_Xs <- data_Xs[rownames(data_Y), ]
}
data_Y <- data.matrix(data_Y)
data_Xs <- data.matrix(data_Xs)
##applying lasso (as implemented in glmnet package, a path of penalization
##parameter lambda according to the MSE computed is computed by 10-fold
##cross-validation)
cvfit <- cv.glmnet(data_Xs, data_Y, family = "gaussian",
alpha = 1)
##Compute predicted Y "Y_predit"
Y_predit <-
predict(cvfit, newx = data_Xs, s = "lambda.min")
##selecting the model with the penalization parameter minimizing MSE
Y_predit <- Y_predit[rownames(Y_predit), ]
##dataframe of predictors selected
tmp_coeffs <-
coef(cvfit, s = "lambda.min")
##selecting the model with the penalization parameter minimizing MSE
cg_select <-
data.frame(name = tmp_coeffs@Dimnames[[1]][tmp_coeffs@i + 1],
coefficient = tmp_coeffs@x)
cg_select <- cg_select$name[cg_select$name != "(Intercept)"]
a <- list()
if (length(cg_select) != 0) {
a <- list("selected" = cg_select,
"prediction" = Y_predit,
"null" = "nul")
} else{
a <-
list(
"selected" = character(),
"prediction" = "pas_de_prediction",
"null" = "nul"
)
}
return(a)
}
####lasso - basic implementation but using lambda.1se instead of lambda.min
#### this includes a basic 10-fold cross
##validation process as implemented in the CVglmnet package
lasso_1SE <-
function(data_Xs_in,
##dataset of explanatory variables ("exposures")
data_Y_in,
##dataset of univariate variable of interest ("outcome")
name_Y,
##variable of interest name
data_covar_in = NULL,
##if neccessary, dataset of covariates ("confounders")
covar = character(0)) {
##if necessary, vector of covariates name
if (length(covar) > 0) {
##if necessary, computing residuals of the linear model explaining the
##variable of interest by the covariates
data_covar <-
data_covar_in[rownames(data_covar_in) %in% rownames(data_Y_in) &
rownames(data_covar_in) %in% rownames(data_Xs_in),
colnames(data_covar_in) %in%
covar, drop = FALSE]
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_covar) &
rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop =
FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_covar) &
rownames(data_Xs_in) %in% rownames(data_Y_in),
, drop = FALSE]
data_covar <- data_covar[rownames(data_Y), ]
data_Xs <- data_Xs[rownames(data_Y), ]
data_Y <- getresiduals_2df(data_Y, data_covar, name_Y, covar)
} else{
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop = FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_Y_in), , drop = FALSE]
data_Xs <- data_Xs[rownames(data_Y), ]
}
data_Y <- data.matrix(data_Y)
data_Xs <- data.matrix(data_Xs)
##applying lasso (as implemented in glmnet package, a path of penalization
##parameter lambda according to the MSE computed is computed by 10-fold
##cross-validation)
cvfit <- cv.glmnet(data_Xs, data_Y, family = "gaussian",
alpha = 1)
##Compute predicted Y "Y_predit"
Y_predit <-
predict(cvfit, newx = data_Xs, s = "lambda.1se")
##selecting the model within 1MSE of the model using
##the penalization parameter minimizing MSE
Y_predit <- Y_predit[rownames(Y_predit), ]
##dataframe of predictors selected
tmp_coeffs <-
coef(cvfit, s = "lambda.min")
##selecting the model with the penalization parameter minimizing MSE
cg_select <-
data.frame(name = tmp_coeffs@Dimnames[[1]][tmp_coeffs@i + 1],
coefficient = tmp_coeffs@x)
cg_select <- cg_select$name[cg_select$name != "(Intercept)"]
a <- list()
if (length(cg_select) != 0) {
a <- list("selected" = cg_select,
"prediction" = Y_predit,
"null" = "nul")
} else{
a <-
list(
"selected" = character(),
"prediction" = "pas_de_prediction",
"null" = "nul"
)
}
return(a)
}
####lasso_stab : implementation of Meinshausen 2010
#### repeating lasso on
##subsamples and performing the selection according to empirical probability of
##selection computed over the repeated runs using a threshold specified by user
lasso_stab_Meinshausen <-
function(data_Xs_in,
##dataset of explanatory variables ("exposures")
data_Y_in,
##dataset of univariate variable of interest ("outcome")
name_Y,
##variable of interest name
data_covar_in = NULL,
##if neccessary, dataset of covariates ("confounders")
covar = character(0),
##if necessary, vector of covariates name
prop = 0.85) {
#minimal threshold for an empirical probability to make the corresponding
#variable selected
if (length(covar) > 0) {
##if necessary, computing residuals of the linear model explaining the
##variable of interest by the covariates
data_covar <-
data_covar_in[rownames(data_covar_in) %in% rownames(data_Y_in) &
rownames(data_covar_in) %in% rownames(data_Xs_in),
colnames(data_covar_in) %in%
covar, drop = FALSE]
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_covar) &
rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop =
FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_covar) &
rownames(data_Xs_in) %in% rownames(data_Y_in),
, drop = FALSE]
data_covar <- data_covar[rownames(data_Y), ]
data_Xs <- data_Xs[rownames(data_Y), ]
data_Y <- getresiduals_2df(data_Y, data_covar, name_Y, covar)
} else{
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) ==
name_Y, drop = FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_Y), , drop = FALSE]
data_Xs <- data_Xs[rownames(data_Y), ]
}
if (is.null(data_Y)) {
stop("Données incohérentes entre elles _ Y")
}
if (is.null(data_Xs)) {
stop("Données incohérentes entre elles _ Xs")
}
if (!(name_Y %in% colnames(data_Y))) {
stop("Données incohérentes entre elles _ nom Y")
}
data_Y <- data.matrix(data_Y)
data_Xs <- data.matrix(data_Xs)
list_iter <- list()
length_lambdas <- numeric()
n_iter_stab <- 100
##setting the number of repetitions from which the empirical probabilities
##will be computed
for (k2 in (1:n_iter_stab)) {
#randomly selecting a subsample containing 50% of individuals
selec <-
sample(rownames(data_Xs), round(1 * nrow(data_Xs) / 2)) #
i_df <- data.matrix(data_Xs[rownames(data_Xs) %in% selec, ])
block_pheno <-
data_Y[rownames(data_Y) %in% rownames(i_df), , drop = FALSE]
block_pheno <- block_pheno[rownames(i_df), , drop = FALSE]
##applying lasso to the subsample
model.lasso <-
glmnet(
x = i_df,
y = data.matrix(block_pheno),
family = "gaussian",
alpha = 1
)
#saving the selection for each lambda in a dataframe
selection_pour_une_iter <-
as.data.frame(cbind(rownames(model.lasso$beta), as.numeric(tabulate(
model.lasso$beta@i + 1
))))
colnames(selection_pour_une_iter) <-
c("variables", paste("iter", k2))
##adding this dataframe to the list of dataframes computed for all
##precedent subsamples
list_iter <- c(list_iter, list(selection_pour_une_iter))
##saving the length of penalization path
length_lambdas <-
c(length_lambdas, length(model.lasso$lambda))
}
##merging all dataframes of selection by variable
M <-
as.data.frame(Reduce(function(x, y)
merge(x, y, by = "variables"), list_iter))
M[, 2:ncol(M)] <-
lapply(M[, 2:ncol(M)], function(x)
as.numeric(as.character(x)))
##summing the frequencies of selection by variables
M$sum <- rowSums(M[, 2:ncol(M)])
M1 <- M[, c(1, ncol(M))]
##computing the empirical probabilities from the sum of frequencies of
##selection by variables and the number of possible selections
M1$proba_estimee <- M1$sum / (sum(length_lambdas))
##selecting variables from the empirical probabilities and the threshold
cg_select <- M1$variables[M1$proba_estimee >= prop]
##returning the selection
a <- list()
if (length(cg_select) != 0) {
a <-
list(
"selected" = cg_select,
"selection_iter" = list(M, M1),
"iteration" = n_iter_stab
)
} else{
a <-
list(
"selected" = character(0),
"selection_iter" = list(M, M1),
"iteration" = n_iter_stab
)
}
return(a)
}
####lasso_stab : second implementation of Meinshausen 2010
#### selection of a
##set of lambda parameters on a subsample then repeating lasso on subsamples
##with those lambdas and performing the selection according to empirical
##probability of selection computed over the repeated runs using a threshold
##specified by user
lasso_stab_Meinshausen2 <-
function(data_Xs_in,
##dataset of explanatory variables ("exposures")
data_Y_in,
##dataset of univariate variable of interest ("outcome")
name_Y,
##variable of interest name
data_covar_in = NULL,
##if neccessary, dataset of covariates ("confounders")
covar = character(0),
##if necessary, vector of covariates names
prop = 0.95) {
#minimal threshold for an empirical probability to make the corresponding
#variable selected
if (length(covar) > 0) {
##if necessary, computing residuals of the linear model explaining the
##variable of interest by the covariates
data_covar <-
data_covar_in[rownames(data_covar_in) %in% rownames(data_Y_in) &
rownames(data_covar_in) %in% rownames(data_Xs_in),
colnames(data_covar_in) %in%
covar, drop = FALSE]
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_covar) &
rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) == name_Y, drop =
FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_covar) &
rownames(data_Xs_in) %in% rownames(data_Y_in), , drop = FALSE]
data_covar <- data_covar[rownames(data_Y), ]
data_Xs <- data_Xs[rownames(data_Y), ]
data_Y <- getresiduals_2df(data_Y, data_covar, name_Y, covar)
} else{
data_Y <-
data_Y_in[rownames(data_Y_in) %in% rownames(data_Xs_in),
colnames(data_Y_in) ==
name_Y, drop = FALSE]
data_Xs <-
data_Xs_in[rownames(data_Xs_in) %in% rownames(data_Y), , drop = FALSE]
data_Xs <- data_Xs[rownames(data_Y), ]
}
if (is.null(data_Y)) {
stop("Données incohérentes entre elles _ Y")
}
if (is.null(data_Xs)) {
stop("Données incohérentes entre elles _ Xs")
}
if (!(name_Y %in% colnames(data_Y))) {
stop("Données incohérentes entre elles _ nom Y")
}
data_Y <- data.matrix(data_Y)
data_Xs <- data.matrix(data_Xs)
list_iter <- list()
###defining a vector of penalized parameters lambda on a subsample
selec <- sample(rownames(data_Xs), round(1 * nrow(data_Xs) / 2))
i_df <- data.matrix(data_Xs[rownames(data_Xs) %in% selec, ])
block_pheno <-
data_Y[rownames(data_Y) %in% rownames(i_df), , drop = FALSE]
block_pheno <- block_pheno[rownames(i_df), , drop = FALSE]
temp <-
glmnet(
x = i_df,
y = block_pheno,
family = "gaussian",
alpha = 1
)
##lasso is applied; the path of lambdas will be used for all other
##subsamples
lambdas <- temp$lambda
###repeating lasso fo all subsamples
n_iter_stab <- 100
##setting the number of repetitions from which the empirical probabilities
##will be computed
for (k2 in (1:n_iter_stab)) {
selec <-
sample(rownames(data_Xs), round(1 * nrow(data_Xs) / 2))
#randomly selecting a subsample containing 50% of individuals
i_df <- data.matrix(data_Xs[rownames(data_Xs) %in% selec, ])
block_pheno <-
data_Y[rownames(data_Y) %in% rownames(i_df), , drop = FALSE]
block_pheno <- block_pheno[rownames(i_df), , drop = FALSE]
##applying lasso to the subsample
model.lasso <-
glmnet(
x = i_df,
y = data.matrix(block_pheno),
family = "gaussian",
alpha = 1,
lambda = as.numeric(lambdas)
)
#saving the selection for each lambda in a dataframe
selection_pour_une_iter <-
as.data.frame(cbind(rownames(model.lasso$beta), as.numeric(tabulate(
model.lasso$beta@i + 1
))))
colnames(selection_pour_une_iter) <-
c("variables", paste("iter ", k2))
##adding this dataframe to the list of dataframes computed for all
##precedent subsamples
list_iter <- c(list_iter, list(selection_pour_une_iter))
}
##merging all dataframe of selection by variable
M <-
as.data.frame(Reduce(function(x, y)
merge(x, y, by = "variables"), list_iter))
M[, 2:ncol(M)] <-
lapply(M[, 2:ncol(M)], function(x)
as.numeric(as.character(x)))
##summing the frequencies of selection by variables
M$sum <- rowSums(M[, 2:ncol(M)])
M1 <- M[, c(1, ncol(M))]
##computing the empirical probabilities from the sum of frequencies of
##selection by variables and the number of possible selections
M1$proba_estimee <- M1$sum / (length(lambdas) * n_iter_stab)
M1$proba_estimee <- M1$sum / (sum(length_lambdas))
##selecting variables from the empirical probabilities and the threshold
cg_select <- M1$variables[M1$proba_estimee >= prop]
##returning the selection
a <- list()
if (length(cg_select) != 0) {
a <-
list(
"selected" = cg_select,
"selection_iter" = list(M, M1),
"iteration" = n_iter_stab
)
} else{
a <-
list(
"selected" = character(0),
"selection_iter" = list(M, M1),
"iteration" = n_iter_stab
)
}
return(a)
}
####LASSO_CV2####
### loop applying 100 times lasso with the 10-fold validations procedures on the
### whole dataset the average of the mean error curves (MSE as a function of the
### MSE) gives the penalization parameter which minimizes this averaged MSE and
### which will be used in the final model
lasso_moy_MSE <-
function(data_Xs_in,
##dataset of explanatory variables ("exposures")
data_Y_in,
##dataset of univariate variable of interest ("outcome")
name_Y,
##variable of interest name
data_covar_in = NULL,
##if neccessary, dataset of covariates ("confounders")
covar = character(0)) {
##if necessary, vector of covariates name
if (length(covar) > 0) {
##if necessary, computing residuals of the linear model explaining the
##variable of interest by the covariates
data_covar <-
data_covar_in[rownames(data_covar_in) %in% rownames(data_Y_in) &
rownames(data_covar_in) %in% rownames(data_Xs_in),
colnames(data_covar_in) %in%
covar, drop = FALSE]
data_Y <-