-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPower functions.R
1177 lines (887 loc) · 51.6 KB
/
Power functions.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
###########################################################################
############################ Power Functions ##############################
###########################################################################
### Please explore these functions using example data sets using the shiny app:
### https://joelarkman.shinyapps.io/PowerTools/
# Simulate log-normal data set from input
simulateLogNormal <- function(data, covType, nsamples) {
message('Simulating Log Normal dataset', appendLF = F)
# Create an offset to allow lof to be taken even for values close to zero.
offset <- abs(min(data)) + 1
# Add offset to data.
offData <- data + offset
# Calculate log of data.
logData <- log(offData)
# Calculate the mean of each column in the data.
meansLog <- colMeans(logData)
if (covType=='Estimate') {
# In estimate mode, compute covariance matrix for input data.
covLog <- cov(logData)
} else if (covType=='Diagonal') {
# In diagonal mode produce only diagonal 1 matrix.
covLog <- diag(1, ncol=ncol(logData), nrow = ncol(logData))
} else {
print('ERROR')
}
# Simulate n samples from multivariate normal distribution using colmeans and covariance matrix.
simData <- MASS::mvrnorm(n=nsamples, mu=meansLog, Sigma = covLog)
# Find exponant to return to original scale.
simData <- exp(simData)
# Remove the initial offset.
simData <- simData - offset
# Set any simulated negative numbers to 0.
simData[simData<0] <- 0
message(' ...complete!')
return(simData)
}
# Calculate confusion matrix.
calcConfMatrixUniv <- function(p,corrVector,signThreshold,corrThresh){
# Examine vector of p-values to identify those below threshold p-value.
Pf <- p < signThreshold
# Create storage variables for the number of..
# True positive variables.
TP <- 0
# True negative variables.
TN <- 0
# False positive vairables.
FP <- 0
# False negative variables.
FN <- 0
# For each of the variables in the data set (which is equal to number of correlation
# values in input vector)
for ( i in 1:length(corrVector)) {
# If the currently iterated variable correlates poorly with the test variable
# and is not found to significantly correlate with Y..
if (abs(corrVector[i]) < corrThresh & Pf[i]==F) {
TN <- TN+1 # Add one to TN count.
# If the currently iterated variable correlates strongly with the test variable
# and is also found to significantly correlate with Y..
} else if (abs(corrVector[i]) > corrThresh & Pf[i]==T) {
TP <- TP+1 # Add one to TP count.
# If the currently iterated variable correlates strongly with the test variable
# but is not found to significantly correlate with Y..
} else if (abs(corrVector[i]) > corrThresh & Pf[i]==F) {
FN <- FN+1 # Add one to FN count.
# If the currently iterated variable correlates poorly with the test variable
# but is found to significantly correlate with Y..
} else if (abs(corrVector[i]) < corrThresh & Pf[i]==T) {
FP <- FP+1 # Add one to FP count.
}
}
# Calculate rates of each output as a proportion of the others.
TNtot <- TN/(FP+TN)
TPtot <- TP/(TP+FN)
FPtot <- FP/(FP+TN)
FNtot <- FN/(TP+FN)
FDtot <- FP/(TP+FP)
# Create list of rate values.
output <- list('TNtot'=TNtot,'TPtot'=TPtot,'FPtot'=FPtot,'FNtot'=FNtot,'FDtot'=FDtot)
# Return list of confusion matrix metrics.
return(output)
}
# Continous outcome power function.
PCalc_Continuous <- function(x,
y=NULL,
sampSizes=NULL,
grouping=T,
signThreshold=0.05,
nSimSamp=5000,
nRepeats=10,
targetVar=NULL){
if (is.null(y)){stop('Y values not provided.')} # Stop if no y data provided.
else if (is.null(sampSizes)){stop('No sample sizes provided.')} # Stop if sample sizes are not provided.
else if (is.null(x)){stop('No x data provided.')} # Stop if no x data is provided.
# Ensure no. simulated samples is larger than largest chosen sample size to evaluate.
if (max(sampSizes) >= nSimSamp){
print(paste('Increasing no. simulated samples to faciltiate assessment
of sample size: ', max(sampSizes),'',sep = ''))
nSimSamp <- max(sampSizes) + 500
}
# Convert x data to data frame (to ensure the presense of column names).
data <- as.data.frame(x)
# Calculate the number of x variables.
numVars <- ncol(data)
# Calculate the number of sample sizes to assess each variable at.
nSampSizes <- length(sampSizes)
# Define the number of effect sizes to assess each variable at to be 1 - their actual effect size.
nEffSizes <- 1
# Estimate effect size of each variable as the absolute value of their correlation with y.
message('Calculating true variable effect sizes', appendLF = F)
effectSizes <- abs(round(cor(x=x, y=y), digits = 2))
message(' ...complete!')
if (grouping==T) { # If grouping is active.
message('Grouping similar variables & extracting group member with largest effect size',
appendLF = F)
# Group similar variables based on hierachicial clustering of distance matrix generated from
# inter-variable correlations.
corr_clustering <- hclust(as.dist(1-abs(cor(na.omit(data)))))
# Cut the tree (and thus define each group) based on height of tree (cut at height = 0.5)
groups <- as.factor(cutree(corr_clustering, h = 0.5))
# Define variables for storage.
out <- NULL
groupSize <- NULL
# For each of the groups identified.
for (i in 1: length(levels(groups))) {
# Extract the names of the variables in the currently iterated group.
tmp_group <- names(groups)[which(groups==levels(groups)[i])]
# Extract the effect size of the variables in the currently iterated group.
features <- effectSizes[which(rownames(effectSizes) %in% tmp_group)]
# Add variable names to the new vector of effect sizes.
names(features) <- tmp_group
# Calculate the size of the current group and append this to storage vector.
groupSize <- c(groupSize,length(features))
# Order the group members accoding to their effect size and extract group
# member with largest effect size.
features <- features[order(features, decreasing = T)][1]
# Add the chosen variable name / effect size for currently iterated group to
# output vector of features to assess.
out <- c(out,features)
}
# Update effectSizes vector to contain only the variables to be assessed.
effectSizes <- out
# Define assessVars as the column number of each of the variables to be assessed.
assessVars <- which(colnames(data) %in% names(out))
# Define namesVars as simply the names of each of the variables to be assessed.
namesVars <- names(out)
message(' ...complete!')
} else if (grouping == F) { # If grouping is inactive.
# Define all variables as assessVars and store their names.
assessVars <- 1:ncol(data)
namesVars <- colnames(data)
groupSize <- NA
}
# Use 'simulateLogNormal' function to produce a simulated dataset of samples
# equal to the provided 'nSimSamp' variable and based on the correlation structure
# of the provided xdata.
Samples <- simulateLogNormal(data, 'Estimate', nSimSamp)
# Produce correlation matrix for the simulated dataset.
message('Calculating correlation structure', appendLF = F)
correlationMat <- cor(Samples)
message(' ...complete!')
message('')
if (!is.null(targetVar)) { # If a targetVar is provided.
# If the provided targetVar is the name of one of the x variables.
if (targetVar %in% colnames(data)) {
# Search for the targetVar within the groups vector and return the number of the group it is within.
# Then, update 'effectSizes' to only contain that of the chosen variable from this group.
effectSizes <- effectSizes[groups[names(groups) %in% targetVar]]
# Similarly, update 'namesVars' and 'assessVars' to only contain the name and column number of the
# chosen variable grouped with targetVar.
namesVars <- namesVars[groups[names(groups) %in% targetVar]]
assessVars <- assessVars[groups[names(groups) %in% targetVar]]
message(paste("Targeting variable: '", targetVar,
"', which is grouped with '", namesVars,"'", sep = ''))
message('')
# If the provided targetVar refers to the column number of one of the x variables.
} else if (targetVar %in% 1:ncol(data)) {
# As above, identify the group targetVar belongs to, the variable chosen
# to represent that group, and update 'effectSizes', 'namesVars' and 'assessVars'
# to contain this variable only.
effectSizes <- effectSizes[groups[names(groups) %in% colnames(data)[targetVar]]]
namesVars <- namesVars[groups[names(groups) %in% colnames(data)[targetVar]]]
assessVars <- assessVars[groups[names(groups) %in% colnames(data)[targetVar]]]
message(paste("Targeting variable: '", targetVar,
"', which is grouped with '", namesVars,"'", sep = ''))
message('')
} else{stop('Invalid target variable')} # If targetVar is anything else, stop.
}
# Initialise output data structure.
output <- NULL
for (i in 1:length(assessVars)) { # For each of the variables to be assessed.
# Store the column number of currently iterated variable as 'currVar'.
currVar <- assessVars[i]
message(paste('(',i, '/', length(assessVars),") Assessing variable '", namesVars[i],
"' (effect size: ", sep = ''), appendLF = F)
# Create storage data structure comprised of multiple matrices with nrows equal
# to the number of effectSizes to assess each variable at (typically 1) and ncols
# equal to the number of sample sizes to assess each variable at.
# Each of these matrices is defined to store calculated 'true positive', 'false positive',
# 'true negative', etc, values for the currently iterated variable when assessed at
# each sample size effect sizes.
# In addition, create three of these large data structures:
# One to store values calculated using uncorrected p-values.
uncStruct <- list('TP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'TN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes))
# One to store values calculated using bonferroni adjusted p-values.
bonfStruct <- list('TP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'TN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes))
# One to store values calculated using benjamini-hochberg adjusted p-values.
bhStruct <- list('TP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'TN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes))
for (currEff in 1:nEffSizes) { # For each of the effect sizes each variable is being assessed at.
# Create storage vector equal to the number of features in data set.
b1 <- rep(0, numVars)
# Store the effect size of the curently iterated variable at the relevent position
# within this storage vector (e.g if variable 4 was being assessed, store its effectSize
# in the fourth position of b1).
b1[currVar] <- effectSizes[i]
message(paste(b1[currVar]), '):')
message('Using sample size: ', appendLF = F)
for (currSampSize in 1:nSampSizes) { # For each sample size each variable is being assessed at.
if(currSampSize==nSampSizes) {
message(paste(sampSizes[currSampSize],'.', sep = ''), appendLF = F)
message()
} else {
message(paste(sampSizes[currSampSize],', ', sep = ''), appendLF = F)
}
# Create tempory storage structures to store the uncorrected and corrected confusion matrix
# values calculated for each of the nRepeats to be conducted.
Results <- data.frame('TP'=rep(0,nRepeats),
'FP'=rep(0,nRepeats),
'TN'=rep(0,nRepeats),
'FN'=rep(0,nRepeats),
'FD'=rep(0,nRepeats))
Bonferroni <- data.frame('TP'=rep(0,nRepeats),
'FP'=rep(0,nRepeats),
'TN'=rep(0,nRepeats),
'FN'=rep(0,nRepeats),
'FD'=rep(0,nRepeats))
BH <- data.frame('TP'=rep(0,nRepeats),
'FP'=rep(0,nRepeats),
'TN'=rep(0,nRepeats),
'FN'=rep(0,nRepeats),
'FD'=rep(0,nRepeats))
# Combine the three lists of storage vectors (one for uncorrected, one for
# bonferroni corrected and one for BH corrected p-values) to create large temporary
# storage structure.
multiplerepeats <- list('Results'=Results,'Bonferroni'=Bonferroni,'BH'=BH)
# Create a progress bar to show position with respect to number of repeats.
#pb <- txtProgressBar(min = 0, max = nRepeats, style = 3)
for (currRepeat in 1:nRepeats) { # For each of the nRepeats
# Generate selection index of random integers of length equal to the currently iterated
# sample size (values between 1 and the number of simulated samples).
selectIndex <- sample.int(nSimSamp, sampSizes[currSampSize])
# Use the selection index to extract a random selection of samples from the simulated
# dataset, equal to the currently iterated sample size.
SelSamples <- Samples[selectIndex,]
# Center and scale the new data subset.
SelSamples <- scale(SelSamples)
# Generate random noise values (mean=0,SD=1) equal to the currently iterated sample size.
noiseLevel <- 1
noise <- noiseLevel * rnorm(sampSizes[currSampSize])
# Generate a vector of y values by multiplying the x-values of the currently iterated variable
# by its effect size and adding the random noise generated above.
Y <- SelSamples[,currVar]*b1[currVar]
Y <- Y + noise
# Create p-value storage vector.
p <- rep(0, numVars)
# Regress each variable in the dataset against Y value vector, extract and store p-values.
for (i in 1:numVars) {
B <- data.frame(Y=Y,X=SelSamples[,i])
if (anyNA(B$X)) {
B <- data.frame(Y=Y,X=SelSamples[,i])
if (anyNA(B$X)) {
p[i] <- 1
next()
}
}
model <- lm(Y~.,B)
p[i] <- summary(model)[[4]][2,4]
}
pUnc <- p # Store uncorrected p-values.
pBonf <- p.adjust(p, method = 'bonferroni') # Apply and store bonferroni correction.
pBH <- p.adjust(p, method = 'BH') # Apply and store BH correction.
# Extract correlation vector pertaining to how each variable in the datset correlates
# with the currently iterated variable.
corrVector <- correlationMat[,currVar]
# Perform 'calcConfMatrixUniv' function using uncorrected, bonferoni corrected and
# BH corrected p-values.
uncorrected <- calcConfMatrixUniv(pUnc,corrVector,signThreshold,0.8)
bonferroni <- calcConfMatrixUniv(pBonf,corrVector,signThreshold,0.8)
bh <- calcConfMatrixUniv(pBH,corrVector,signThreshold,0.8)
# Store the uncorrected confusion matrix output values for the current repeat.
multiplerepeats$Results$TP[currRepeat] <- uncorrected$TPtot
multiplerepeats$Results$FP[currRepeat] <- uncorrected$FPtot
multiplerepeats$Results$TN[currRepeat] <- uncorrected$TNtot
multiplerepeats$Results$FN[currRepeat] <- uncorrected$FNtot
multiplerepeats$Results$FD[currRepeat] <- uncorrected$FDtot
# Store the bonferroni corrected confusion matrix output values for the current repeat.
multiplerepeats$Bonferroni$TP[currRepeat] <- bonferroni$TPtot
multiplerepeats$Bonferroni$FP[currRepeat] <- bonferroni$FPtot
multiplerepeats$Bonferroni$TN[currRepeat] <- bonferroni$TNtot
multiplerepeats$Bonferroni$FN[currRepeat] <- bonferroni$FNtot
multiplerepeats$Bonferroni$FD[currRepeat] <- bonferroni$FDtot
# Store the BH corrected confusion matrix output values for the current repeat.
multiplerepeats$BH$TP[currRepeat] <- bh$TPtot
multiplerepeats$BH$FP[currRepeat] <- bh$FPtot
multiplerepeats$BH$TN[currRepeat] <- bh$TNtot
multiplerepeats$BH$FN[currRepeat] <- bh$FNtot
multiplerepeats$BH$FD[currRepeat] <- bh$FDtot
#setTxtProgressBar(pb, currRepeat) # Update progress bar.
}
# close(pb) # Terminate progress bar.
# Extract the names of each of the confusion matrix metrics (e.g. TP, FP, TN, FN and FD).
stats <- colnames(multiplerepeats$Bonferroni)
for (nstat in 1:5) { # For each of the metrics
# Define currstat as the name of the currently iterated metric.
currstat <- stats[nstat]
# Store the average uncorrected confusion matrix values (across repeats) generated
# using the currently iterated variable, effect size and sample size.
uncStruct[[which(names(uncStruct)%in%stats[nstat])]][currEff,currSampSize] <-
mean(multiplerepeats$Results[,which(names(multiplerepeats$Results)%in%stats[nstat])])
# Store the standard deviation of the uncorrected confusion matrix values (across repeats)
# generated using the currently iterted variable, effect size and sample size.
uncStruct[[which(names(uncStruct)%in%paste('S',stats[nstat],sep = ''))]][currEff,currSampSize] <-
sd(multiplerepeats$Results[,which(names(multiplerepeats$Results)%in%stats[nstat])])
# Store the average bonferroni corrected confusion matrix values (across repeats) generated
# using the currently iterated variable, effect size and sample size.
bonfStruct[[which(names(bonfStruct)%in%stats[nstat])]][currEff,currSampSize] <-
mean(multiplerepeats$Bonferroni[,which(names(multiplerepeats$Bonferroni)%in%stats[nstat])])
# Store the standard deviation of the bonferroni corrected confusion matrix values (across repeats)
# generated using the currently iterted variable, effect size and sample size.
bonfStruct[[which(names(bonfStruct)%in%paste('S',stats[nstat],sep = ''))]][currEff,currSampSize] <-
sd(multiplerepeats$Bonferroni[,which(names(multiplerepeats$Bonferroni)%in%stats[nstat])])
# Store the average BH corrected confusion matrix values (across repeats) generated
# using the currently iterated variable, effect size and sample size.
bhStruct[[which(names(bhStruct)%in%stats[nstat])]][currEff,currSampSize] <-
mean(multiplerepeats$BH[,which(names(multiplerepeats$BH)%in%stats[nstat])])
# Store the standard deviation of the BH corrected confusion matrix values (across repeats)
# generated using the currently iterted variable, effect size and sample size.
bhStruct[[which(names(bhStruct)%in%paste('S',stats[nstat],sep = ''))]][currEff,currSampSize] <-
sd(multiplerepeats$BH[,which(names(multiplerepeats$BH)%in%stats[nstat])])
}
}
}
# Combine each of the storage data structures for the currently iterated variable
# into single storeVar 'list'.
storeVar <- list('Uncorrected'=uncStruct,'Bonferroni'=bonfStruct,'BH'=bhStruct)
# Append the storeVar structure for the currently iterated variable to the main output data structure.
output <- c(output, list(storeVar))
message('')
}
# Define the names of each list entry of the main output data structure as the names of each of the
# assessed variables.
names(output) <- namesVars
# Create a list of the input parameters provided to the function to faciliate subsequent plotting.
input_params <- list('effectSizes'=effectSizes,
'sampSizes'=sampSizes,
'assessVars'=assessVars,
'namesVars'=namesVars,
'groupSize'=groupSize,
'targetVar'=!is.null(targetVar),
'numSamps'=nrow(data))
# Append the list of input parameters to the main output data structure.
output <- c(output, 'input_params'= list(input_params))
# Add S3 class of 'PCalc' to main output data structure.
class(output) <- c('PCalc','list')
# Return main output data structure.
return(output)
}
# Two-group classification outcome power function.
PCalc_2Group <- function(x,
y=NULL,
n_controls=NULL,
control_group =NULL,
sampSizes=NULL,
grouping=T,
signThreshold=0.05,
nSimSamp=500,
nRepeats=10,
targetVar=NULL){
if (is.null(y)){stop('Y values not provided.')} # Stop if no y data provided.
else if (is.null(sampSizes)){stop('No sample sizes provided.')} # Stop if sample sizes are not provided.
else if (is.null(x)){stop('No x data provided.')} # Stop if no x data is provided.
# Ensure no. simulated samples is larger than largest chosen sample size to evaluate.
if (2*(max(sampSizes)) >= nSimSamp){
print(paste('Increasing no. simulated samples to faciltiate assessment
of sample size: ', max(sampSizes),sep = ''))
nSimSamp <- 2*(max(sampSizes)) + 500
}
y <- as.factor(y)
if (length(levels(y))!=2){stop('More than two Y groups were provided')}
if (!is.null(control_group)) {
case_group <- as.character(y[y != control_group][1])
y <- factor(y, levels = c(case_group, control_group))
}
x <- as.data.frame(x)
data <- as.data.frame(rbind(x[y %in% levels(y)[1],],
x[y %in% levels(y)[2],]))
y_ordered <- c(y[y %in% levels(y)[1]],
y[y %in% levels(y)[2]])
# Calculate the number of x variables.
numVars <- ncol(data)
# Calculate the number of sample sizes to assess each variable at.
nSampSizes <- length(sampSizes)
# Define the number of effect sizes to assess each variable at to be 1 - their actual effect size.
nEffSizes <- 1
# Estimate effect size of each variable as the absolute value of their correlation with y.
message('Calculating true variable effect sizes', appendLF = F)
effectSizes <- NULL
for (i in 1:numVars) {
n1 <- length(which(y_ordered==1))
n2 <- length(which(y_ordered==2))
m1 <- mean(data[which(y_ordered==1),i])
m2 <- mean(data[which(y_ordered==2),i])
S1 <- var(data[which(y_ordered==1),i])
S2 <- var(data[which(y_ordered==2),i])
s <- sqrt((((n1-1)*(S1)) + ((n2-1)*(S2)))/(n1+n2-2))
d <- abs(round((m1-m2)/s,2))
effectSizes <- c(effectSizes,d)
}
names(effectSizes) <- colnames(data)
message(' ...complete!')
if (grouping==T) { # If grouping is active.
message('Grouping similar variables & extracting group member with largest effect size',
appendLF = F)
# Group similar variables based on hierachicial clustering of distance matrix generated from
# inter-variable correlations.
corr_clustering <- hclust(as.dist(1-abs(cor(na.omit(data)))))
# Cut the tree (and thus define each group) based on height of tree (cut at height = 0.5)
groups <- as.factor(cutree(corr_clustering, h = 0.5))
# Define variables for storage.
out <- NULL
groupSize <- NULL
# For each of the groups identified.
for (i in 1: length(levels(groups))) {
# Extract the names of the variables in the currently iterated group.
tmp_group <- names(groups)[which(groups==levels(groups)[i])]
# Extract the effect size of the variables in the currently iterated group.
features <- effectSizes[which(names(effectSizes) %in% tmp_group)]
# Add variable names to the new vector of effect sizes.
names(features) <- tmp_group
# Calculate the size of the current group and append this to storage vector.
groupSize <- c(groupSize,length(features))
# Order the group members accoding to their effect size and extract group
# member with largest effect size.
features <- features[order(features, decreasing = T)][1]
# Add the chosen variable name / effect size for currently iterated group to
# output vector of features to assess.
out <- c(out,features)
}
# Update effectSizes vector to contain only the variables to be assessed.
effectSizes <- out
# Define assessVars as the column number of each of the variables to be assessed.
assessVars <- which(colnames(data) %in% names(out))
# Define namesVars as simply the names of each of the variables to be assessed.
namesVars <- names(out)
message(' ...complete!')
} else if (grouping == F) { # If grouping is inactive.
# Define all variables as assessVars and store their names.
assessVars <- 1:ncol(data)
namesVars <- colnames(data)
groupSize <- NA
}
# Use 'simulateLogNormal' function to produce a simulated dataset of samples
# equal to the provided 'nSimSamp' variable and based on the correlation structure
# of the provided xdata.
Samples <- simulateLogNormal(data, 'Estimate', nSimSamp)
# Produce correlation matrix for the simulated dataset.
message('Calculating correlation structure', appendLF = F)
correlationMat <- cor(Samples)
message(' ...complete!')
message('')
if (!is.null(targetVar)) { # If a targetVar is provided.
# If the provided targetVar is the name of one of the x variables.
if (targetVar %in% colnames(data)) {
# Search for the targetVar within the groups vector and return the number of the group it is within.
# Then, update 'effectSizes' to only contain that of the chosen variable from this group.
effectSizes <- effectSizes[groups[names(groups) %in% targetVar]]
# Similarly, update 'namesVars' and 'assessVars' to only contain the name and column number of the
# chosen variable grouped with targetVar.
namesVars <- namesVars[groups[names(groups) %in% targetVar]]
assessVars <- assessVars[groups[names(groups) %in% targetVar]]
message(paste("Targeting variable: '", targetVar,
"', which is grouped with '", namesVars,"'", sep = ''))
message('')
# If the provided targetVar refers to the column number of one of the x variables.
} else if (targetVar %in% 1:ncol(data)) {
# As above, identify the group targetVar belongs to, the variable chosen
# to represent that group, and update 'effectSizes', 'namesVars' and 'assessVars'
# to contain this variable only.
effectSizes <- effectSizes[groups[names(groups) %in% colnames(data)[targetVar]]]
namesVars <- namesVars[groups[names(groups) %in% colnames(data)[targetVar]]]
assessVars <- assessVars[groups[names(groups) %in% colnames(data)[targetVar]]]
message(paste("Targeting variable: '", targetVar,
"', which is grouped with '", namesVars,"'", sep = ''))
message('')
} else{stop('Invalid target variable')} # If targetVar is anything else, stop.
}
# Initialise output data structure.
output <- NULL
for (i in 1:length(assessVars)) { # For each of the variables to be assessed.
# Store the column number of currently iterated variable as 'currVar'.
currVar <- assessVars[i]
message(paste('(',i, '/', length(assessVars),") Assessing variable '", namesVars[i],
"' (effect size: ", sep = ''), appendLF = F)
# Create storage data structure comprised of multiple matrices with nrows equal
# to the number of effectSizes to assess each variable at (typically 1) and ncols
# equal to the number of sample sizes to assess each variable at.
# Each of these matrices is defined to store calculated 'true positive', 'false positive',
# 'true negative', etc, values for the currently iterated variable when assessed at
# each sample size effect sizes.
# In addition, create three of these large data structures:
# One to store values calculated using uncorrected p-values.
uncStruct <- list('TP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'TN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes))
# One to store values calculated using bonferroni adjusted p-values.
bonfStruct <- list('TP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'TN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes))
# One to store values calculated using benjamini-hochberg adjusted p-values.
bhStruct <- list('TP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'TN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'FD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFP'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'STN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFN'=matrix(0,nrow=nEffSizes,ncol=nSampSizes),
'SFD'=matrix(0,nrow=nEffSizes,ncol=nSampSizes))
for (currEff in 1:nEffSizes) { # For each of the effect sizes each variable is being assessed at.
# Create storage vector equal to the number of features in data set.
b1 <- rep(0, numVars)
# Store the effect size of the curently iterated variable at the relevent position
# within this storage vector (e.g if variable 4 was being assessed, store its effectSize
# in the fourth position of b1).
b1[currVar] <- effectSizes[i]
message(paste(b1[currVar]), '):')
message('Using sample size: ', appendLF = F)
for (currSampSize in 1:nSampSizes) { # For each sample size each variable is being assessed at.
if(currSampSize==nSampSizes) {
message(paste(sampSizes[currSampSize],'.', sep = ''), appendLF = F)
message()
} else {
message(paste(sampSizes[currSampSize],', ', sep = ''), appendLF = F)
}
# Create tempory storage structures to store the uncorrected and corrected confusion matrix
# values calculated for each of the nRepeats to be conducted.
Results <- data.frame('TP'=rep(0,nRepeats),
'FP'=rep(0,nRepeats),
'TN'=rep(0,nRepeats),
'FN'=rep(0,nRepeats),
'FD'=rep(0,nRepeats))
Bonferroni <- data.frame('TP'=rep(0,nRepeats),
'FP'=rep(0,nRepeats),
'TN'=rep(0,nRepeats),
'FN'=rep(0,nRepeats),
'FD'=rep(0,nRepeats))
BH <- data.frame('TP'=rep(0,nRepeats),
'FP'=rep(0,nRepeats),
'TN'=rep(0,nRepeats),
'FN'=rep(0,nRepeats),
'FD'=rep(0,nRepeats))
# Combine the three lists of storage vectors (one for uncorrected, one for
# bonferroni corrected and one for BH corrected p-values) to create large temporary
# storage structure.
multiplerepeats <- list('Results'=Results,'Bonferroni'=Bonferroni,'BH'=BH)
# Create a progress bar to show position with respect to number of repeats.
#pb <- txtProgressBar(min = 0, max = nRepeats, style = 3)
for (currRepeat in 1:nRepeats) { # For each of the nRepeats
if (is.null(n_controls)) {
m <- 2*(sampSizes[currSampSize])
} else {
m <- sampSizes[currSampSize] + n_controls
}
# Generate selection index of random integers of length equal to the currently iterated
# sample size (values between 1 and the number of simulated samples).
#selectIndex <- sample.int(nrow(Samples), (1+controlgroupWeight)*sampSizes[currSampSize])
selectIndex <- sample.int(nrow(Samples), m)
# Use the selection index to extract a random selection of samples from the simulated
# dataset, equal to the currently iterated sample size.
SelSamples <- Samples[selectIndex,]
# Assume class balanced.
GroupId=rep(1,nrow(SelSamples))
GroupId[(round(sampSizes[currSampSize])+1):length(GroupId)] <- 2
# Extract correlation vector pertaining to how each variable in the datset correlates
# with the currently iterated variable.
corrVector <- correlationMat[,currVar]
# Introduce difference between classes.
for (i in 1:numVars){
if (abs(corrVector[i])>0.8) {
SelSamples[GroupId==2,i] <- SelSamples[GroupId==2,i] + b1[currVar]*sd(SelSamples[,i])
}
}
# Center and scale the new data subset.
SelSamples <- scale(SelSamples)
# Create p-value storage vector.
p <- rep(0, numVars)
# Conduct anova for each variable in the dataset, extract and store p-values.
for (i in 1:numVars) {
model <- aov(x~group, data=data.frame(x=SelSamples[,i], group=GroupId))
p[i] <- summary(model)[[1]][1,5]
}
pUnc <- p # Store uncorrected p-values.
pBonf <- p.adjust(p, method = 'bonferroni') # Apply and store bonferroni correction.
pBH <- p.adjust(p, method = 'BH') # Apply and store BH correction.
# Perform 'calcConfMatrixUniv' function using uncorrected, bonferoni corrected and
# BH corrected p-values.
uncorrected <- calcConfMatrixUniv(pUnc,corrVector,signThreshold,0.8)
bonferroni <- calcConfMatrixUniv(pBonf,corrVector,signThreshold,0.8)
bh <- calcConfMatrixUniv(pBH,corrVector,signThreshold,0.8)
# Store the uncorrected confusion matrix output values for the current repeat.
multiplerepeats$Results$TP[currRepeat] <- uncorrected$TPtot
multiplerepeats$Results$FP[currRepeat] <- uncorrected$FPtot
multiplerepeats$Results$TN[currRepeat] <- uncorrected$TNtot
multiplerepeats$Results$FN[currRepeat] <- uncorrected$FNtot
multiplerepeats$Results$FD[currRepeat] <- uncorrected$FDtot
# Store the bonferroni corrected confusion matrix output values for the current repeat.
multiplerepeats$Bonferroni$TP[currRepeat] <- bonferroni$TPtot
multiplerepeats$Bonferroni$FP[currRepeat] <- bonferroni$FPtot
multiplerepeats$Bonferroni$TN[currRepeat] <- bonferroni$TNtot
multiplerepeats$Bonferroni$FN[currRepeat] <- bonferroni$FNtot
multiplerepeats$Bonferroni$FD[currRepeat] <- bonferroni$FDtot
# Store the BH corrected confusion matrix output values for the current repeat.
multiplerepeats$BH$TP[currRepeat] <- bh$TPtot
multiplerepeats$BH$FP[currRepeat] <- bh$FPtot
multiplerepeats$BH$TN[currRepeat] <- bh$TNtot
multiplerepeats$BH$FN[currRepeat] <- bh$FNtot
multiplerepeats$BH$FD[currRepeat] <- bh$FDtot
#setTxtProgressBar(pb, currRepeat) # Update progress bar.
}
# close(pb) # Terminate progress bar.
# Extract the names of each of the confusion matrix metrics (e.g. TP, FP, TN, FN and FD).
stats <- colnames(multiplerepeats$Bonferroni)
for (nstat in 1:5) { # For each of the metrics
# Define currstat as the name of the currently iterated metric.
currstat <- stats[nstat]
# Store the average uncorrected confusion matrix values (across repeats) generated
# using the currently iterated variable, effect size and sample size.
uncStruct[[which(names(uncStruct)%in%stats[nstat])]][currEff,currSampSize] <-
mean(multiplerepeats$Results[,which(names(multiplerepeats$Results)%in%stats[nstat])])
# Store the standard deviation of the uncorrected confusion matrix values (across repeats)
# generated using the currently iterted variable, effect size and sample size.
uncStruct[[which(names(uncStruct)%in%paste('S',stats[nstat],sep = ''))]][currEff,currSampSize] <-
sd(multiplerepeats$Results[,which(names(multiplerepeats$Results)%in%stats[nstat])])
# Store the average bonferroni corrected confusion matrix values (across repeats) generated
# using the currently iterated variable, effect size and sample size.
bonfStruct[[which(names(bonfStruct)%in%stats[nstat])]][currEff,currSampSize] <-
mean(multiplerepeats$Bonferroni[,which(names(multiplerepeats$Bonferroni)%in%stats[nstat])])
# Store the standard deviation of the bonferroni corrected confusion matrix values (across repeats)
# generated using the currently iterted variable, effect size and sample size.
bonfStruct[[which(names(bonfStruct)%in%paste('S',stats[nstat],sep = ''))]][currEff,currSampSize] <-
sd(multiplerepeats$Bonferroni[,which(names(multiplerepeats$Bonferroni)%in%stats[nstat])])
# Store the average BH corrected confusion matrix values (across repeats) generated
# using the currently iterated variable, effect size and sample size.
bhStruct[[which(names(bhStruct)%in%stats[nstat])]][currEff,currSampSize] <-
mean(multiplerepeats$BH[,which(names(multiplerepeats$BH)%in%stats[nstat])])
# Store the standard deviation of the BH corrected confusion matrix values (across repeats)
# generated using the currently iterted variable, effect size and sample size.
bhStruct[[which(names(bhStruct)%in%paste('S',stats[nstat],sep = ''))]][currEff,currSampSize] <-
sd(multiplerepeats$BH[,which(names(multiplerepeats$BH)%in%stats[nstat])])
}
}
}
# Combine each of the storage data structures for the currently iterated variable
# into single storeVar 'list'.
storeVar <- list('Uncorrected'=uncStruct,'Bonferroni'=bonfStruct,'BH'=bhStruct)
# Append the storeVar structure for the currently iterated variable to the main output data structure.
output <- c(output, list(storeVar))
message('')
}
# Define the names of each list entry of the main output data structure as the names of each of the
# assessed variables.
names(output) <- namesVars
# Create a list of the input parameters provided to the function to faciliate subsequent plotting.
input_params <- list('effectSizes'=effectSizes,
'sampSizes'=sampSizes,
'assessVars'=assessVars,
'namesVars'=namesVars,
'groupSize'=groupSize,
'targetVar'=!is.null(targetVar),
'numSamps'=nrow(data))
# Append the list of input parameters to the main output data structure.
output <- c(output, 'input_params'= list(input_params))
# Add S3 class of 'PCalc' to main output data structure.
class(output) <- c('PCalc','list')
# Return main output data structure.
return(output)
}
# Plotting function.
power_plot <- function(output, correction, metric){
# Ensure ggplot2 package is loaded.
require('ggplot2')
# Ensure reshape2 package is loaded.
require('reshape2')
# Define index for correction type and metric.
correction_index <- c('Uncorrected', 'Bonferroni', 'BH')
metric_index <- c('TP', 'FP','TN','FN','FD','STP','SFP','STN','SFN','SFD')
# Stop if 'output' object is not of class 'PCalc'
if (!inherits(output, 'PCalc')) {
stop("Must provide valid output object of class 'PCalc'.")
# Stop if correction value is not a valid option.
} else if (!correction %in% correction_index) {
stop("Must provide valid correction value: 'Uncorrected', 'Bonferroni' or 'BH'.")
# Stop if metric value is not a valid option.
} else if (!metric %in% metric_index) {
stop("Must provide valid metric value: 'TP', 'FP','TN','FN' or 'FD'.")
}
# Extract input_parameters from 'PCalc' output object.
sampSizes <- output$input_params$sampSizes
effectSizes <- output$input_params$effectSizes
assessVars <- output$input_params$assessVars
namesVars <- output$input_params$namesVars
groupSize <- output$input_params$groupSize
targetVar <- output$input_params$targetVar
numSamps <- output$input_params$numSamps