-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnalyticalPipeline_v1.0.0.Rmd
2838 lines (1850 loc) · 117 KB
/
AnalyticalPipeline_v1.0.0.Rmd
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
---
title: "Analytical pipeline for testing the performance of sleep-tracking technology v1.0.0"
author: Luca Menghini,$^{1,2}$ \and
Nicola Cellini,$^{2,3,4,5}$ \and
Aimee Goldstone,$^1$ \and
Fiona C. Baker,$^{1,6}$ \and
Massimiliano de Zambotti$^1$
date: $^1$Center for Health Sciences, SRI International, Menlo Park, CA, USA; \newline
$^2$Department of General Psychology, University of Padova, Padua, Italy; \newline
$^3$Padova Neuroscience Center, University of Padova, Padua, Italy; \newline
$^4$Department of Biomedical Sciences, University of Padova, Padua, Italy; \newline
$^5$Human Inspired Technology Center, University of Padova, Padua, Italy; \newline
$^6$Brain Function Research Group, School of Psychology, University of the Witwatersrand, Johannesburg, South Africa \newline
\newline
\newline
\today
output:
html_document:
df_print: paged
toc: true
toc_float: true
css: styles.css
pdf_document: default
word_document: default
theme: united
---
<br>
# Aims and content
The present document integrates the article “A standardized framework for testing the performance of sleep-tracking technology: Step-by-step guidelines and open-source code”, and it includes the code for running the essential steps to test the performance of a device under assessment (e.g., a consumer wearable sleep-tracking device) in measuring sleep as compared with the gold-standard reference method (polysomnography, PSG) or alternative reference method (e.g., actigraphy, sleep diary).
The functions depicted below are available also from the following public repository: https://github.com/SRI-human-sleep/sleep-trackers-performance )
The document includes the following sections:
1. **Data structure**: a sample dataset with the essential epoch-by-epoch data structure is loaded and considered the starting point for analyses.
2. **Discrepancy analysis**: individual- and group-level sleep measures are generated for both the reference method and the device under assessment, along with their bias, the limits of agreement (LoAs), and their 95% confidence intervals. Bland-Altman plots are provided.
3. **Epoch-by-epoch analysis**: error matrices (also referred to as confusion matrices), performance metrics at both the individual- and group-level, and secondary statistics are generated based on epoch-by-epoch data.
A function is provided for each step of the pipeline, which can be applied to any dataset that meets the assumptions below, to generate the respective output.
<br>
## Glossary
- PSG = Polysomnography
- TIB = Time in bed
- TST = Total Sleep Time
- SOL = Sleep Onset Latency
- SE = Sleep Efficiency
- WASO = Wake After Sleep Onset
- REM = Rapid Eye Movement
- EBE = Epoch-by-Epoch
- PPV = Positive Predictive Value
- NPV = Negative Predictive Value
- PABAK = Prevalence-Adjusted Bias-Adjusted Kappa
- ROC = Receiver Operating Characteristic
<br>
Note also that in the new generation of multi-sensor sleep-tracking devices providing sleep staging information, ‘Light Sleep’ is usually considered equivalent to PSG-derived N1 + N2 sleep, while ‘Deep Sleep’ is usually considered equivalent to PSG-derived N3 sleep. When testing the performance of a device, we recommend checking with the device manufacturer for sleep stage specification.
<br>
## Assumptions
The starting point of each of the following steps is a data structure based on the following assumptions:
<div class="alert alert-info">
**- Measurement systems:** sleep has been measured with both a *device* under assessment (e.g., a consumer sleep tracker) and a *reference* method (e.g., *PSG*)
**- Epoch length**: both device and reference recordings have the same epoch length (e.g. 30-seconds or 1-min level).
**- Recording bounds**: both device and reference recordings are confined to the period between lights-off and lights-on (i.e., both recordings share the same time in bed).
**- Synchronization**: the device and reference recordings have been synchronized on an epoch level and encoded using the same coding system (e.g. 0 = wake in both device and reference data).
**- Staging**: the device provides information on PSG-equivalent sleep staging, either as sleep/wake (typical of standard actigraphy) or as wake/light/deep/REM (typical of more modern consumer sleep trackers).
**- Number of nights**: only one night per subject has been recorded (the same procedures might apply to multiple nights, by aggregating night-by-night outcomes).
**- Missing data**: the dataset should not contain any missing data (i.e., both device and reference information must exist for each epoch).
<br>
Please refer to de Zambotti et al. (2019) and Depner et al. (2019) for guidelines and details about implementation and use of consumer sleep technology.
</div>
```{r setup, echo=FALSE,warning=FALSE,message=FALSE}
rm(list=ls())
```
<br>
# 1. Data structure {.tabset .tabset-fade .tabset-pills}
As a first step, we load a sample dataset organized with the data structure described in the main article.
<br>
## SLEEP STAGING
<br>
Here, we show the dataset with sleep stage information, encoded as: 0 = wake, 1 = light sleep (N1 or N2), 2 = deep sleep (N3), and 3 = REM sleep. The dataset is in a long format that includes one column with the subject identifier, one column for the epoch identifier, and two columns reporting the device and the reference data, respectively.
```{r warning=FALSE,message=FALSE}
(raw.data <- read.csv("sample_data.csv"))
```
<br>
## SLEEP/WAKE
<br>
To account for cases where only sleep/wake dichotomous data are allowed by the device, we also recode our sample dataset with 10 = wake and 5 = sleep.
```{r warning=FALSE,message=FALSE}
# dichotomic recoding of raw dataset
dic.data <- raw.data
dic.data[dic.data$reference!=0,"reference"] = 5 # 5 when sleep
dic.data[dic.data$reference==0,"reference"] = 10 # 10 when wake
dic.data[dic.data$device!=0,"device"] = 5
dic.data[dic.data$device==0,"device"] = 10
dic.data
```
<br>
# 2. Discrepancy analysis
As a second step, we perform the essential procedures to analyze the discrepancy between device- and reference-derived sleep measures (e.g., total sleep time, wake after sleep onset, sleep onset latency). For each measure, the discrepancies will be computed at both individual-level and group-level, and Bland-Altman plots will be generated.
<br>
## 2.1. Sleep measures computation {.tabset .tabset-fade .tabset-pills}
First, the raw data are used to generate a dataset of sleep measures based on the definitions provided in the main article. This is done with the **ebe2sleep.R** function, which allows users to specify the following arguments:
- *data*: data.frame including the raw data to be used, organized with the data structure shown above.
- *idCol*, *RefCol* and *deviceCol*: character strings indicating the names of the columns for subjects, reference and device epochs, respectively.
- *epochLength*: numeric value indicating the epoch duration in seconds (default: 30).
- *staging*: logical value indicates whether the raw data includes sleep stages (wake, light, deep and REM) or not, FALSE assumes data consists of only wake/sleep distinction (default: TRUE).
- *stages*: numeric vector indicating the coding system used for wake, light, deep and REM sleep (in this order). The default coding system is c(wake = 0, light = 1, deep = 2, REM = 3). Only wake and sleep should be indicated when staging = FALSE, e.g. c(wake = 0, sleep = 1).
- *digits*: numeric value specifying the decimal precision for the output (default: 2).
<br>
<details><summary>Show function</summary>
<p>
```{r warning=FALSE,message=FALSE}
ebe2sleep <- function(data=NA,idCol="subject",RefCol="reference",deviceCol="device",epochLenght=30,
staging=TRUE,stages=c(wake=0,light=1,deep=2,REM=3),digits=2){
# renaming variables
colnames(data) <- gsub(idCol,"ID",colnames(data))
data$ID <- as.factor(data$ID)
colnames(data) <- gsub(RefCol,"ref",colnames(data))
colnames(data) <- gsub(deviceCol,"device",colnames(data))
# setting stages as 0 = wake, 1 = light, 2 = deep, 3 = REM
if(staging==TRUE){
data$ref <- as.integer(as.character(factor(data$ref,levels=as.numeric(stages),labels=c(0,1,2,3))))
data$device <- as.integer(as.character(factor(data$device,levels=as.numeric(stages),labels=c(0,1,2,3))))
} else { # setting stages as 0 = wake, 1 = sleep when staging = FALSE
if(length(stages)>2){ stop("only two elements should be used in the stages argument when staging = FALSE,
e.g., stages = c(wake = 0, sleep = 1)") }
data$ref <- as.integer(as.character(factor(data$ref,levels=as.numeric(stages),labels=c(0,1))))
data$device <- as.integer(as.character(factor(data$device,levels=as.numeric(stages),labels=c(0,1)))) }
# empty dataframe of sleep measures (stages length is not provided when staging = FALSE)
sleep.metrics <- as.data.frame(matrix(nrow=0,ncol=ifelse(staging==TRUE,22,10)))
for(ID in levels(data$ID)){
sleepID <- data[data$ID==ID,]
# TIB = number of minutes between lights on and lights off
TIB <- nrow(sleepID)*epochLenght/60
# TST = number of minutes scored as sleep
TST_ref <- nrow(sleepID[sleepID$ref!=0,])*epochLenght/60
TST_device <- nrow(sleepID[sleepID$device!=0,])*epochLenght/60
# SE = percentage of sleep time over TIB
SE_ref <- 100*TST_ref/TIB
SE_device <- 100*TST_device/TIB
# SOL = number of minutes scored as wake before the first epoch scored as sleep
SOL_ref = SOL_device = 0
for(i in 1:nrow(sleepID)){ if(sleepID[i,"ref"]==0){ SOL_ref = SOL_ref + 1 } else { break } }
for(i in 1:nrow(sleepID)){ if(sleepID[i,"device"]==0){ SOL_device = SOL_device + 1 } else { break } }
SOL_ref <- SOL_ref*epochLenght/60
SOL_device <- SOL_device*epochLenght/60
# WASO = number of minutes scored as wake after the first epoch scored as sleep
WASO_ref <- sleepID[(SOL_ref*60/epochLenght+1):nrow(sleepID),]
WASO_ref <- nrow(WASO_ref[WASO_ref$ref==0,])*epochLenght/60
WASO_device <- sleepID[(SOL_device*60/epochLenght+1):nrow(sleepID),]
WASO_device <- nrow(WASO_device[WASO_device$device==0,])*epochLenght/60
if(staging==TRUE){
# Light = number of minutes scored as Light sleep (N1 + N2)
Light_ref <- nrow(sleepID[sleepID$ref==1,])*epochLenght/60
Light_device <- nrow(sleepID[sleepID$device==1,])*epochLenght/60
# Deep = number of minutes scored as Light sleep (N3)
Deep_ref <- nrow(sleepID[sleepID$ref==2,])*epochLenght/60
Deep_device <- nrow(sleepID[sleepID$device==2,])*epochLenght/60
# REM = number of minutes scored as REM sleep
REM_ref <- nrow(sleepID[sleepID$ref==3,])*epochLenght/60
REM_device <- nrow(sleepID[sleepID$device==3,])*epochLenght/60
# LightPerc = percentage of Light sleep over TST
LightPerc_ref <- 100*Light_ref/TST_ref
LightPerc_device <- 100*Light_device/TST_device
# DeepPerc = percentage of Deep sleep over TST
DeepPerc_ref <- 100*Deep_ref/TST_ref
DeepPerc_device <- 100*Deep_device/TST_device
# REMPerc = percentage of REM sleep over TST
REMPerc_ref <- 100*REM_ref/TST_ref
REMPerc_device <- 100*REM_device/TST_device
# filling dataframe of sleep metrics
sleep.metrics <- rbind(sleep.metrics,
data.frame(subject=ID,TIB=TIB,
# sleep/wake metrics
TST_ref,TST_device,SE_ref,SE_device,SOL_ref,SOL_device,WASO_ref,WASO_device,
# sleep stages duration metrics
Light_ref,Light_device,Deep_ref,Deep_device,REM_ref,REM_device,
# sleep stages percentages metrics
LightPerc_ref,LightPerc_device,DeepPerc_ref,DeepPerc_device,REMPerc_ref,REMPerc_device))
} else {
sleep.metrics <- rbind(sleep.metrics,
data.frame(subject=ID,TIB=TIB,
# sleep/wake metrics
TST_ref,TST_device,SE_ref,SE_device,SOL_ref,SOL_device,WASO_ref,WASO_device))
}
}
# rounding values and returning dataset
nums <- vapply(sleep.metrics, is.numeric, FUN.VALUE = logical(1))
sleep.metrics[,nums] <- round(sleep.metrics[,nums], digits = digits)
return(sleep.metrics)
}
```
</p>
</details>
<br>
### SLEEP STAGING
<br>
Here, we use the function to generate the dataset of sleep measures by assuming that sleep staging is allowed by the device.
```{r warning=FALSE,message=FALSE}
(sleep.data <- ebe2sleep(data = raw.data, idCol = "subject", RefCol = "reference", deviceCol = "device",
epochLenght = 30, staging = TRUE, stages = c(wake = 0, light = 1, deep = 2, REM = 3), digits = 2))
```
<br>
### SLEEP/WAKE
<br>
Here, we use the function to generate the dataset of sleep measures by assuming that only sleep/wake patterns (and not sleep staging) are allowed by the device.
```{r warning=FALSE,message=FALSE}
(sleep.data.dic <- ebe2sleep(data = dic.data, idCol = "subject", RefCol = "reference", deviceCol = "device",
epochLenght = 30, staging = FALSE, stages = c(wake = 10, sleep = 5), digits = 2))
```
<br>
## 2.2. Individual-level discrepancies {.tabset .tabset-fade .tabset-pills}
Here, we compute the differences between device- and reference -derived sleep measures for each subject. This is done with the **indDiscr.R function**, which allows the user to specify the following arguments:
- *data*: data.frame of sleep measures (such that generated with the *ebe2sleep.R* function).
- *staging*: logical value indicates whether the raw data includes sleep stages (wake, light, deep and REM) or not, FALSE assumes data consists of only wake/sleep distinction (default: TRUE).
- *digits*: numeric value specifying the decimal precision for the output (default: 2).
- *doPlot*: logical value indicating if the data should be plotted (default: TRUE, requires the *ggplot2* and the *reshape2* package).
<br>
<details><summary>Show function</summary>
<p>
```{r warning=FALSE,message=FALSE}
indDiscr <- function(data=NA,staging=TRUE,digits=2,doPlot=TRUE){
indivDiscr <- data.frame(subject=data$subject,
TST_diff = data$TST_device - data$TST_ref, # TST
SE_diff = data$SE_device - data$SE_ref, # SE
SOL_diff = data$SOL_device - data$SOL_ref, # SOL
WASO_diff = data$WASO_device - data$WASO_ref) # WASO
if(staging==TRUE){
indivDiscr <- cbind(indivDiscr,
data.frame(
# adding sleep stages duration
Light_diff = data$Light_device - data$Light_ref,
Deep_diff = data$Deep_device - data$Deep_ref,
REM_diff = data$REM_device - data$REM_ref,
# adding sleep stages percentages
LightPerc_diff = data$LightPerc_device - data$LightPerc_ref,
DeepPerc_diff = data$DeepPerc_device - data$DeepPerc_ref,
REMPerc_diff = data$REMPerc_device - data$REMPerc_ref
))
}
# rounding values
nums <- vapply(indivDiscr, is.numeric, FUN.VALUE = logical(1))
indivDiscr[,nums] <- round(indivDiscr[,nums], digits = digits)
if(doPlot==TRUE){
require(ggplot2)
require(reshape2)
# normalizing data by column to have color code
melted.perc <- absDiscr <- indivDiscr
absDiscr[,2:ncol(absDiscr)] <- abs(absDiscr[,2:ncol(absDiscr)])
for(i in 1:nrow(melted.perc)){ for(j in 2:ncol(melted.perc)){
melted.perc[i,j] <- 100*(absDiscr[i,j] - min(absDiscr[,j]))/(max(absDiscr[,j])-min(absDiscr[,j]))
} }
melted.perc <- melt(melted.perc[,!grepl("diffPerc",colnames(melted.perc))])
melted.perc$variable <- gsub("Perc","%",gsub("_diff","",melted.perc$variable))
melted.perc[melted.perc$value>100,"value"] <- 100 # bounding at 100
melted.labs <- melt(indivDiscr[,!grepl("diffPerc",colnames(indivDiscr))])
melted.labs$variable <- gsub("Perc","%",gsub("_diff","",melted.labs$variable))
# sorting axis labels
if(staging == TRUE){ sleep.levels <- c("TST","SE","WASO","SOL","Light","Deep","REM","Light%","Deep%","REM%")
} else { sleep.levels <- c("TST","SE","WASO","SOL") }
# generating plot
p <- ggplot(data=melted.perc,aes(x=ordered(variable,levels=sleep.levels),
y=ordered(subject,levels=rev(levels(subject))),fill=value)) +
geom_tile() + xlab("variable") + ylab("subject") +
scale_fill_gradient2(low="white",high="#f03b20",
limit = c(0,100),
space = "Lab",
name="Min-max normalized \ndiscrepancy (%)",
guide="legend",
breaks=round(seq(100,0,length.out = 11),2),
minor_breaks=round(seq(100,0,length.out = 11),2)) +
geom_text(data=melted.labs,aes(x=ordered(variable,levels=sleep.levels),
y=ordered(subject,levels=rev(levels(subject))),label=value),color="black",size=3) +
ggtitle("Discrepancies between device and ref by subject") + theme(panel.background = element_blank())
return(list(indivDiscr,p))
} else { return(indivDiscr) }
}
```
</p>
</details>
<br>
### SLEEP STAGING
<br>
Here, the function is applied to generate individual discrepancies by assuming that sleep staging is allowed by the device.
```{r warning=FALSE,message=FALSE,out.width='55%'}
indDiscr(data = sleep.data, staging=TRUE, digits=2, doPlot = FALSE)
```
<br>
### SLEEP/WAKE
<br>
Here, the function is applied to generate individual discrepancies by assuming that only sleep/wake patterns (and not sleep staging) are allowed by the device.
```{r warning=FALSE,message=FALSE,out.width='55%'}
indDiscr(data = sleep.data.dic, staging=FALSE, digits=2, doPlot = FALSE)
```
<br>
## 2.2.1. Data visualization {.tabset .tabset-fade .tabset-pills}
Here, we set the *doPlot* argument as TRUE in the *DiscrAnalysis_ind* function to plot the results. The generated plot (table format) includes the same values shown in the table above, with colors indicating the minimum-maximum, normalized values. This allows a visual check for outliers for each of the main sleep outcomes.
<br>
### SLEEP STAGING
<br>
Here, the function is applied by assuming that sleep staging is allowed by the device.
```{r warning=FALSE,message=FALSE,out.width='70%'}
indDiscr(data = sleep.data, staging=TRUE, digits=2, doPlot = TRUE)[2]
```
<br>
### SLEEP/WAKE
<br>
Here, the function is applied by assuming that only sleep/wake patterns (and not sleep staging) are allowed by the device.
```{r warning=FALSE,message=FALSE,out.width='70%'}
indDiscr(data = sleep.data.dic, staging=FALSE, digits=2, doPlot = TRUE)[2]
```
<br>
## 2.3. Group-level discrepancies {.tabset .tabset-fade .tabset-pills}
Here, we compute the standard metrics to evaluate the discrepancy/agreement between device- and reference-derived sleep measures, based on the definitions provided in the main article, in compliance with Bland and Altman (1999). As recommended by Euser, Dekker and le Cessie (2008), when a significant correlation is observed between differences and PSG-derived measures (proportional bias), the LOAs are indicated as a function of the PSG-derived value. This is done with the **groupDiscr.R function**, which allows specification of the following arguments:
- *data*: data.frame of sleep measures with a structure matching that generated with the *ebe2sleep.R* function).
- *measures*: character vector indicating the name of the two columns to be considered (i.e., fist column: device, second column: reference). Default is c("TST_device","TST_ref").
- *size*: character indicating what should be used as the size of measurement: “reference” (default) for using the reference method as we suggest in our article, “mean” for using the averages of ref- and device-derived measures, as originally suggested by Bland & Altman (1999).
- *logTransf*: logical value indicating if data should be log transformed to deal with heteroscedasticity or non-normal distribution of differences (default: FALSE). If TRUE, data bias and LOAs are computed on the log-transformed data and back-transformed to express LOAs as a function of the size of measurement, following the method proposed by Euser, Dekker and le Cessie (2008).
- *CI.type*: character string indicating the type of confidence intervals to be used: "classic" (default) returns intervals based on the t-distribution, "boot" returns intervals computed by bootstrap with 10000 replicates (requires the *boot* package).
- *CI.level*: numeric value indicating the confidence intervals to be computed on bias and LOAs (default: .95).
- *boot.type*: character string indicating the type of bootstrapped confidence intervals. The value should be one of "basic" (default), "norm", "stud", "perc", or "bca" (see *?boot.ci* for details). This argument is not considered when CI.type = "classic".
- *boot.R*: numeric value indicating the number of boostrap replicates (default: 10,000). Higher values require more time for computing CI (see also *?boot*). This argument is not considered when CI.type = "classic".
- *digits*: numeric value specifying the decimal precision for the output (default: 2).
- *warnings*: logical value indicating if warnings regarding assumptions and analytical details should be displayed (default: TRUE).
The function is partially based on the *BlandAltmanLeh* package (Lehnert, 2015).
<br>
<details><summary>Show function</summary>
<p>
```{r warning=FALSE,message=FALSE}
groupDiscr <- function(data=NA,measures=c("TST_device","TST_ref"),size="reference",logTransf=FALSE,
CI.type="classic",CI.level=.95,boot.type="basic",boot.R=10000,digits=2,warnings=TRUE){
require(BlandAltmanLeh)
# setting measure name and unit of measurement
measure <- gsub("_ref","",gsub("_device","",measures[1]))
if(any(grepl("efficiency|EFFICIENCY|se|SE|eff|EFF|perc|Perc|PERC|%",measure))){
meas.unit <- "%" } else { meas.unit <- "min" }
if(warnings==TRUE){cat("\n\n----------------\n Measure:",measure,"\n----------------")}
# packages and functions to be used with boostrap CI
if(CI.type=="boot"){ require(boot)
# functions to generate bootstrap CI for model parameters
boot.reg <- function(data,formula,indices){ return(coef(lm(formula,data=data[indices,]))[2]) } # slope
boot.int <- function(data,formula,indices){ return(coef(lm(formula,data=data[indices,]))[1]) } # intercept
boot.res <- function(data,formula,indices){return(1.96*sd(resid(lm(formula,data=data[indices,]))))} # 1.96 SD of residuals
if(warnings==TRUE){cat("\n\nComputing boostrap CI with method '",boot.type,"' ...",sep="")}
} else if(CI.type!="classic") { stop("Error: CI.type can be either 'classic' or 'boot'") }
# data to be used
ba.stat <- bland.altman.stats(data[,measures[1]],data[,measures[2]],conf.int=CI.level)
if(size=="reference"){
ba <- data.frame(size=ba.stat$groups$group2,diffs=ba.stat$diffs)
xlab <- paste("Reference-derived",measure)
} else if(size=="mean"){
ba <- data.frame(size=ba.stat$means,diffs=ba.stat$diffs)
xlab <- paste("Mean",measure,"by device and reference")
} else { stop("Error: size argument can be either 'reference' or 'mean'") }
# basic output table
out <- data.frame(measure=paste(measure," (",meas.unit,")",sep=""),
# mean and standard deviation for ref and device
device = paste(round(mean(ba.stat$groups$group1,na.rm=TRUE),digits)," (",
round(sd(ba.stat$groups$group1,na.rm=TRUE),digits),")",sep=""),
reference = paste(round(mean(ba.stat$groups$group2,na.rm=TRUE),digits)," (",
round(sd(ba.stat$groups$group2,na.rm=TRUE),digits),")",sep=""),
# CI type
CI.type=CI.type,
CI.level=CI.level)
# ..........................................
# 1. TESTING PROPORTIONAL BIAS
# ..........................................
m <- lm(diffs~size,ba)
if(CI.type=="classic"){ CI <- confint(m,level=CI.level)[2,]
} else { CI <- boot.ci(boot(data=ba,statistic=boot.reg,formula=diffs~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5] }
prop.bias <- ifelse(CI[1] > 0 | CI[2] < 0, TRUE, FALSE)
# updating output table
out <- cbind(out,prop.bias=prop.bias)
# ...........................................
# 1.1. DIFFERENCES INDEPENDENT FROM SIZE
# ...........................................
if(prop.bias == FALSE){
if(CI.type=="boot"){ # changing bias CI when CI.type="boot"
ba.stat$CI.lines[3] <- boot.ci(boot(ba$diffs,function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][4]
ba.stat$CI.lines[4] <- boot.ci(boot(ba$diffs,function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][5] }
out <- cbind(out, # updating output table
# bias (SD) [CI]
bias=paste(round(ba.stat$mean.diffs,digits)," (",round(sd(ba.stat$diffs),digits),")",sep=""),
bias_CI=paste("[",round(ba.stat$CI.lines[3],digits),", ",round(ba.stat$CI.lines[4],digits),"]",sep=""))
# ..........................................
# 1.2. DIFFERENCES PROPORTIONAL TO SIZE
# ..........................................
} else {
b0 <- coef(m)[1]
b1 <- coef(m)[2]
# warning message
if(warnings==TRUE){cat("\n\nWARNING: differences in ",measure," might be proportional to the size of measurement (coeff. = ",
round(b1,2)," [",round(CI[1],2),", ",round(CI[2],2),"]",").",
"\nBias and LOAs are represented as a function of the size of measurement.",sep="")}
# intercept CI
if(CI.type=="classic"){ CInt <- confint(m,level=CI.level)[1,]
} else { CInt <- boot.ci(boot(data=ba,statistic=boot.int,formula=diffs~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5] }
out <- cbind(out, # updating output table
# bias and CI following Bland & Altman (1999): D = b0 + b1 * size
bias=paste(round(b0,digits)," + ",round(b1,digits)," x ",ifelse(size=="mean","mean","ref"),sep=""),
bias_CI=paste("b0 = [",round(CInt[1],digits),", ",round(CInt[2],digits),
"], b1 = [",round(CI[1],digits),", ",round(CI[2],digits),"]",sep="")) }
# ..............................................
# 2. LOAs ESTIMATION FROM ORIGINAL DATA
# ..............................................
if(logTransf == FALSE){
# testing heteroscedasticity
mRes <- lm(abs(resid(m))~size,ba)
if(CI.type=="classic"){ CIRes <- confint(mRes,level=CI.level)[2,]
} else { CIRes <- boot.ci(boot(data=ba,statistic=boot.reg,formula=abs(resid(m))~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5] }
heterosced <- ifelse(CIRes[1] > 0 | CIRes[2] < 0,TRUE,FALSE)
# testing normality of differences
shapiro <- shapiro.test(ba.stat$diffs)
if(shapiro$p.value <= .05){ normality = FALSE
if(warnings==TRUE){cat("\n\nWARNING: differences in ",measure,
" might be not normally distributed (Shapiro-Wilk W = ",round(shapiro$statistic,3),", p = ",round(shapiro$p.value,3),
").","\nBootstrap CI (CI.type='boot') and log transformation (logTransf=TRUE) are recommended.",sep="")}
} else { normality = TRUE }
# updating output table
out <- cbind(out[,1:6],logTransf=FALSE,normality=normality,heterosced=heterosced,out[,7:ncol(out)])
# ...............................................
# 2.1. CONSTANT BIAS AND HOMOSCEDASTICITY
# ............................................
if(prop.bias==FALSE & heterosced==FALSE){
if(CI.type=="boot"){ # changing LOAs CI when CI.type="boot"
ba.stat$CI.lines[1] <- boot.ci(boot(ba$diffs-1.96*sd(ba.stat$diffs),
function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][4]
ba.stat$CI.lines[2] <- boot.ci(boot(ba$diffs-1.96*sd(ba.stat$diffs),
function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][5]
ba.stat$CI.lines[5] <- boot.ci(boot(ba$diffs+1.96*sd(ba.stat$diffs),
function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][4]
ba.stat$CI.lines[6] <- boot.ci(boot(ba$diffs+1.96*sd(ba.stat$diffs),
function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][5] }
out <- cbind(out, # updating output table
# lower LOA and CI
LOA.lower = ba.stat$lower.limit,
LOA.lower_CI = paste("[",round(ba.stat$CI.lines[1],2),", ",round(ba.stat$CI.lines[2],digits),"]",sep=""),
# upper LOA and CI
LOA.upper = ba.stat$upper.limit,
LOA.upper_CI = paste("[",round(ba.stat$CI.lines[5],2),", ",round(ba.stat$CI.lines[6],digits),"]",sep=""))
# ...............................................
# 2.2. PROPORTIONAL BIAS AND HOMOOSCEDASTICITY
# ...............................................
} else if(prop.bias==TRUE & heterosced==FALSE) {
# boostrapped CI in any case
if(warnings==TRUE){cat("\n\nLOAs CI are computed using boostrap with method '",boot.type,"'.",sep="")}
require(boot)
boot.res <- function(data,formula,indices){return(1.96*sd(resid(lm(formula,data=data[indices,]))))} # 1.96 SD of residuals
CI.sdRes <- boot.ci(boot(data=ba,statistic=boot.res,formula=diffs~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5]
out <- cbind(out, # updating output table
# lower LOA and CI following Bland & Altman (1999): LOAs = bias - 1.96sd of the residuals
LOA.lower = paste("bias -",round(1.96*sd(resid(m)),digits)),
LOA.lower_CI = paste("bias - [",round(CI.sdRes[1],digits),", ",round(CI.sdRes[2],digits),"]",sep=""),
# upper LOA and CI following Bland & Altman (1999): LOAs = bias + 1.96sd of the residuals
LOA.upper = paste("bias +",round(1.96*sd(resid(m)),digits)),
LOA.upper_CI =paste("bias + [",round(CI.sdRes[1],digits),", ",round(CI.sdRes[2],digits),"]",sep=""))
# ............................................
# 2.3. HETEROSCEDASTICITY
# ............................................
} else if(heterosced==TRUE){
c0 <- coef(mRes)[1]
c1 <- coef(mRes)[2]
# warning message
if(warnings==TRUE){cat("\n\nWARNING: standard deviation of differences in ",measure,
" might be proportional to the size of measurement (coeff. = ",
round(c1,digits)," [",round(CIRes[1],digits),", ",round(CIRes[2],digits),"]",").",
"\nLOAs range is represented as a function of the size of measurement.",sep="")}
# intercept CI
if(CI.type=="classic"){ CInt <- confint(mRes,level=CI.level)[1,]
} else { CInt <- boot.ci(boot(data=ba,statistic=boot.int,formula=abs(resid(m))~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5] }
out <- cbind(out, # updating output table
# lower LOA and CI following Bland & Altman (1999): LOAs = meanDiff - 2.46(c0 + c1A)
LOA.lower = paste("bias - 2.46(",round(c0,digits)," + ",round(c1,digits)," x ",
ifelse(size=="mean","mean","ref"),")",sep=""),
LOA.lower_CI = paste("c0 = [",round(CInt[1],digits),", ",round(CInt[2],digits),
"], c1 = [",round(CIRes[1],digits),", ",round(CIRes[2],digits),"]",sep=""),
# upper LOA and CI following Bland & Altman (1999): LOAs = meanDiff - 2.46(c0 + c1A)
LOA.upper = paste("bias + 2.46(",round(c0,digits)," + ",round(c1,digits)," x ",
ifelse(size=="mean","mean","ref"),")",sep=""),
LOA.upper_CI = paste("c0 = [",round(CInt[1],digits),", ",round(CInt[2],digits),
"], c1 = [",round(CIRes[1],digits),", ",round(CIRes[2],digits),"]",sep="")) }
# ..............................................
# 3. LOAs ESTIMATION FROM LOG-TRANSFORMED DATA
# ..............................................
} else {
# log transformation of data (add little constant to avoid Inf values)
if(warnings==TRUE){cat("\n\nLog transforming the data before computing LOAs...")}
ba.stat$groups$LOGgroup1 <- log(ba.stat$groups$group1 + .0001)
ba.stat$groups$LOGgroup2 <- log(ba.stat$groups$group2 + .0001)
ba.stat$groups$LOGdiff <- ba.stat$groups$LOGgroup1 - ba.stat$groups$LOGgroup2
if(size=="reference"){ baLog <- data.frame(size=ba.stat$groups$LOGgroup2,diffs=ba.stat$groups$LOGdiff)
} else { baLog <- data.frame(size=(ba.stat$groups$LOGgroup1 + ba.stat$groups$LOGgroup2)/2,diffs=ba.stat$groups$LOGdiff) }
# testing heteroscedasticity
mRes <- lm(abs(resid(m))~size,baLog)
if(CI.type=="classic"){ CIRes <- confint(mRes,level=CI.level)[2,]
} else { CIRes <- boot.ci(boot(data=baLog,statistic=boot.reg,formula=abs(resid(m))~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5] }
heterosced <- ifelse(CIRes[1] > 0 | CIRes[2] < 0,TRUE,FALSE)
# testing normality of differences
shapiro <- shapiro.test(baLog$diffs)
if(shapiro$p.value <= .05){ normality = FALSE
if(warnings==TRUE){cat("\n\nWARNING: differences in log transformed ",measure,
" might be not normally distributed (Shapiro-Wilk W = ",round(shapiro$statistic,3),", p = ",round(shapiro$p.value,3),
").","\nBootstrap CI (CI.type='boot') are recommended.",sep="")} } else { normality = TRUE }
# updating output table
out <- cbind(out[,1:6],logTransf=TRUE,normality=normality,heterosced=heterosced,out[,7:ncol(out)])
# LOAs slope following Euser et al (2008) for antilog transformation: slope = 2 * (e^(1.96 SD) - 1)/(e^(1.96 SD) + 1)
ANTILOGslope <- function(x){ 2 * (exp(1.96 * sd(x)) - 1) / (exp(1.96*sd(x)) + 1) }
ba.stat$LOA.slope <- ANTILOGslope(baLog$diffs)
# LOAs CI slopes
if(CI.type=="classic"){ # classic CI
t1 <- qt((1 - CI.level)/2, df = ba.stat$based.on - 1) # t-value right
t2 <- qt((CI.level + 1)/2, df = ba.stat$based.on - 1) # t-value left
ba.stat$LOA.slope.CI.upper <- 2 * (exp(1.96 * sd(baLog$diffs) + t2 * sqrt(sd(baLog$diffs)^2 * 3/ba.stat$based.on)) - 1) /
(exp(1.96*sd(baLog$diffs) + t2 * sqrt(sd(baLog$diffs)^2 * 3/ba.stat$based.on)) + 1)
ba.stat$LOA.slope.CI.lower <- 2 * (exp(1.96 * sd(baLog$diffs) + t1 * sqrt(sd(baLog$diffs)^2 * 3/ba.stat$based.on)) - 1) /
(exp(1.96*sd(baLog$diffs) + t1 * sqrt(sd(baLog$diffs)^2 * 3/ba.stat$based.on)) + 1)
} else { # boostrap CI
ba.stat$LOA.slope.CI.lower <- boot.ci(boot(baLog$diffs,function(dat,idx) ANTILOGslope(dat[idx]),R=boot.R),
type=boot.type,conf=CI.level)[[4]][4]
ba.stat$LOA.slope.CI.upper <- boot.ci(boot(baLog$diffs,function(dat,idx) ANTILOGslope(dat[idx]),R=boot.R),
type=boot.type,conf=CI.level)[[4]][5] }
# LOAs depending on mean and size (regardless if bias is proportional or not)
out <- cbind(out, # updating output table
# lower LOA and CI
LOA.lower = paste("bias - ",size," x ",round(ba.stat$LOA.slope,digits)),
LOA.lower_CI = paste("bias - ",size," x [",round(ba.stat$LOA.slope.CI.lower,digits),
", ",round(ba.stat$LOA.slope.CI.upper,digits),"]",sep=""),
# upper LOA and CI
LOA.upper = paste("bias + ",size," x ",round(ba.stat$LOA.slope,digits)),
LOA.upper_CI = paste("bias + ",size," x [",round(ba.stat$LOA.slope.CI.lower,digits),
", ",round(ba.stat$LOA.slope.CI.upper,digits),"]",sep="")) }
# rounding values
nums <- vapply(out, is.numeric, FUN.VALUE = logical(1))
out[,nums] <- round(out[,nums], digits = digits)
out[,nums] <- as.character(out[,nums]) # to prevent NA values when combined with other cases
row.names(out) <- NULL
return(out)
}
```
</p>
</details>
<br>
Here, the function is applied to the dataset generated with the *EBE2sleep* function. The *rbind* function is used to concatenate the information on each stage in a single output. The *CI.type* and the *logTransf* arguments are manipulated among sleep measures to show differences between the function settings. Note that a warning is returned in cases where a proportional bias and/or heteroscedasticity is detected (in these cases, the discrepancy metrics are computed according to the procedures described in the main article) or when the distribution of differences deviates from normality (i.e., based on the Shapiro-Wilk test).
<br>
### SLEEP STAGING
<br>
Here, the function is applied by assuming that sleep staging is allowed by the device.
```{r warning=FALSE,message=FALSE}
# boostrapped CI on original data
rbind(groupDiscr(data = sleep.data, measures=c("TST_device","TST_ref"), size="reference",
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("SE_device","SE_ref"), size="reference",
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("SOL_device","SOL_ref"), size="reference",
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("WASO_device","WASO_ref"), size="reference",
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("Light_device","Light_ref"), size="reference",
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("Deep_device","Deep_ref"), size="reference",
CI.type="boot", CI.level=.95, digits=2),
# bootstrapped CI on log-transformed data
groupDiscr(data = sleep.data, measures=c("REM_device","REM_ref"), size = "reference", logTransf = TRUE,
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("LightPerc_device","LightPerc_ref"), size = "reference", logTransf = TRUE,
CI.type="boot",boot.type="basic",CI.level=.95, digits=2),
# classic CI on log-transformed data
groupDiscr(data = sleep.data, measures=c("DeepPerc_device","DeepPerc_ref"), size ="reference", logTransf = TRUE,
CI.type="classic", boot.type="basic", CI.level=.95, digits=2),
groupDiscr(data = sleep.data, measures=c("REMPerc_device","REMPerc_ref"), size="reference", logTransf = TRUE,
CI.type="classic",boot.type="basic",CI.level=.95, digits=2))
```
<br>
### SLEEP/WAKE
<br>
Here, the function is applied by assuming that only sleep/wake patterns (and not sleep staging) are allowed by the device.
```{r warning=FALSE,message=FALSE,out.width='60%'}
rbind(groupDiscr(data = sleep.data.dic, measures=c("TST_device","TST_ref"),
CI.type="boot", CI.level=.95, digits=2),
groupDiscr(data = sleep.data.dic, measures=c("SE_device","SE_ref"), logTransf = TRUE,
CI.type="boot", boot.type="basic", CI.level=.95, digits=2),
groupDiscr(data = sleep.data.dic, measures=c("SOL_device","SOL_ref"),
CI.type="classic", CI.level=.95, digits=2),
groupDiscr(data = sleep.data.dic, measures=c("WASO_device","WASO_ref"), logTransf = TRUE,
CI.type="classic",boot.type="basic", CI.level=.95, digits=2))
```
<br>
## 2.4. Bland-Altman plots {.tabset .tabset-fade .tabset-pills}
The final step for discrepancy analysis uses the information reported above to generate the Bland-Altman plots. This is done with the **BAplot.R** function, which requires the *BlandAltmanLeh*, the *ggplot2* and *ggExtra* packages, and allows the user to specify the following arguments:
- *data*: data.frame of sleep measures (such as that generated with the *ebe2sleep.R* function).
- *measures*: character vector indicating the name of the two columns to be considered (i.e., fist column: device indicated by "measure_device", second column: reference indicated by "measure_ref"). Default is c("TST_device","TST_ref").
- *xaxis*: character indicating what should be used as the x axis: "reference" (default) for using the reference method as we suggest in our article, "mean" for using the averages of ref- and device-derived measures, as originally suggested by Bland & Altman (1999).
- *logTransf*: logical value indicating if data should be log transformed to deal with heteroscedasticity or non-normal distribution of differences (default: FALSE). If TRUE, data bias and LOAs are computed on the log-transformed data and back-transformed to express LOAs as a function of the size of measurement, following the method proposed by Euser, Dekker and le Cessie (2008).
- *CI.type*: character string indicating the type of confidence intervals to be used: "classic" (default) returns intervals based on the t-distribution, "boot" returns intervals for means by bootstrap with 10000 replicates (requires *boot* package).
- *CI.level*: numeric value indicating the confidence intervals to be computed on bias and LOAs (default: .95).
- *boot.type*: character string indicating the type of bootstrapped confidence intervals. The value should be one of "basic" (default), "norm", "stud", "perc", or "bca" (see *?boot.ci* for details). Note that when a proportional bias is detected, only "basic" bootstrapped CI are shown. This argument is not considered when CI.type = "classic".
- *boot.R*: numeric value indicating the number of boostrap replicates (default: 10,000). Higher values require more time for computing CI (see also *?boot*). This argument is not considered when CI.type = "classic".
- *xlim* and *ylim*: numeric vector of two elements indicating the limits of the x and the y axis, respectively. If not specified (default), limits are selected based on the range of differences.
- *warnings*: logical value indicating if warnings regarding assumptions and analytical details should be displayed (default: TRUE).
<br>
<details><summary>Show function</summary>
<p>
```{r }
BAplot <- function(data=NA,measures=c("TST_device","TST_ref"),logTransf=FALSE,
xaxis="reference",CI.type="classic",CI.level=.95,boot.type="basic",boot.R=10000,
xlim=NA,ylim=NA,warnings=TRUE){
require(BlandAltmanLeh); require(ggplot2); require(ggExtra)
# setting labels
Measure <- gsub("_ref","",gsub("_device","",measures[1]))
measure <- gsub("TST","total sleep time (min)",Measure)
measure <- gsub("SE","sleep efficiency (%)",measure)
measure <- gsub("SOL","sleep onset latency (min)",measure)
measure <- gsub("WASO","wake after sleep onset (min)",measure)
measure <- gsub("LightPerc","light sleep percentage (%)",measure)
measure <- gsub("DeepPerc","deep sleep percentage (%)",measure)
measure <- gsub("REMPerc","REM sleep percentage (%)",measure)
measure <- gsub("Light","light sleep duration (min)",measure)
measure <- gsub("Deep","deep sleep duration (min)",measure)
if(grepl("REM",measure) & !grepl("%",measure)) { measure <- gsub("REM","REM sleep duration (min)",measure) }
if(warnings==TRUE){cat("\n\n----------------\n Measure:",Measure,"\n----------------")}
# packages and functions to be used with boostrap CI
if(CI.type=="boot"){ require(boot)
# function to generate bootstrap CI for model parameters
boot.reg <- function(data,formula,indices){ return(coef(lm(formula,data=data[indices,]))[2]) }
# function for sampling and predicting Y values based on model
boot.pred <- function(data,formula,tofit) { indices <- sample(1:nrow(data),replace = TRUE)
return(predict(lm(formula,data=data[indices,]), newdata=data.frame(tofit))) }
if(warnings==TRUE){cat("\n\nComputing boostrap CI with method '",boot.type,"' ...",sep="")}
} else if(CI.type!="classic") { stop("Error: CI.type can be either 'classic' or 'boot'") }
# data to be used
ba.stat <- bland.altman.stats(data[,measures[1]],data[,measures[2]],conf.int=CI.level)
if(xaxis=="reference"){
ba <- data.frame(size=ba.stat$groups$group2,diffs=ba.stat$diffs)
xlab <- paste("Reference",measure)
} else if(xaxis=="mean"){
ba <- data.frame(size=ba.stat$means,diffs=ba.stat$diffs)
xlab <- paste("Mean",measure,"by device and reference")
} else { stop("Error: xaxis argument can be either 'reference' or 'mean'") }
# range of values to be fitted for drawing the lines (i.e., from min to max of x-axis values, by .1)
size <- seq(min(ba$size),max(ba$size),(max(ba$size)-min(ba$size))/((max(ba$size)-min(ba$size))*10))
# basic plot
p <- ggplot(data=ba,aes(size,diffs))
# ..........................................
# 1. TESTING PROPORTIONAL BIAS
# ..........................................
m <- lm(diffs~size,ba)
if(CI.type=="classic"){ CI <- confint(m,level=CI.level)[2,]
} else { CI <- boot.ci(boot(data=ba,statistic=boot.reg,formula=diffs~size,R=boot.R),
type=boot.type,conf=CI.level)[[4]][4:5] }
prop.bias <- ifelse(CI[1] > 0 | CI[2] < 0, TRUE, FALSE)
# ...........................................
# 1.1. DIFFERENCES INDEPENDENT FROM SIZE
# ...........................................
if(prop.bias == FALSE){
if(CI.type=="boot"){ # changing bias CI when CI.type="boot"
ba.stat$CI.lines[3] <- boot.ci(boot(ba$diffs,function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][4]
ba.stat$CI.lines[4] <- boot.ci(boot(ba$diffs,function(dat,idx)mean(dat[idx],na.rm=TRUE),R=boot.R),
type=boot.type,conf=CI.level)[[4]][5] }
p <- p + # adding lines to plot
# bias and CI (i.e., mean diff)
geom_line(aes(y=ba.stat$mean.diffs),colour="red",size=1.5) +
geom_line(aes(y=ba.stat$CI.lines[3]),colour="red",linetype=2,size=1) +
geom_line(aes(y=ba.stat$CI.lines[4]),colour="red",linetype=2,size=1)
# ..........................................
# 1.2. DIFFERENCES PROPORTIONAL TO SIZE
# ..........................................
} else {
b0 <- coef(m)[1]
b1 <- coef(m)[2]
# warning message
if(warnings==TRUE){cat("\n\nWARNING: differences in ",Measure," might be proportional to the size of measurement (coeff. = ",
round(b1,2)," [",round(CI[1],2),", ",round(CI[2],2),"]",").",
"\nBias and LOAs are plotted as a function of the size of measurement.",sep="")}
# modeling bias following Bland & Altman (1999): D = b0 + b1 * size
y.fit <- data.frame(size,y.bias=b0+b1*size)
# bias CI
if(CI.type=="classic"){ # classic ci
y.fit$y.biasCI.upr <- predict(m,newdata=data.frame(y.fit$size),interval="confidence",level=CI.level)[,3]
y.fit$y.biasCI.lwr <- predict(m,newdata=data.frame(y.fit$size),interval="confidence",level=CI.level)[,2]
} else { # boostrap CI
fitted <- t(replicate(boot.R,boot.pred(ba,"diffs~size",y.fit))) # sampling CIs
y.fit$y.biasCI.upr <- apply(fitted,2,quantile,probs=c((1-CI.level)/2))
y.fit$y.biasCI.lwr <- apply(fitted,2,quantile,probs=c(CI.level+(1-CI.level)/2)) }
p <- p + # adding lines to plot
# bias and CI (i.e., D = b0 + b1 * size)
geom_line(data=y.fit,aes(y=y.bias),colour="red",size=1.5) +
geom_line(data=y.fit,aes(y=y.biasCI.upr),colour="red",linetype=2,size=1) +
geom_line(data=y.fit,aes(y=y.biasCI.lwr),colour="red",linetype=2,size=1) }