-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathPopulationSettings.R
More file actions
522 lines (456 loc) · 19.9 KB
/
Copy pathPopulationSettings.R
File metadata and controls
522 lines (456 loc) · 19.9 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
# @file PopulationSettings.R
#
# Copyright 2025 Observational Health Data Sciences and Informatics
#
# This file is part of CohortMethod
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#' create the study population settings
#'
#' @param binary Forces the outcomeCount to be 0 or 1 (use for binary prediction problems)
#' @param includeAllOutcomes (binary) indicating whether to include people with outcomes who are not observed for the whole at risk period
#' @param firstExposureOnly Should only the first exposure per subject be included? Note that
#' this is typically done in the \code{createStudyPopulation} function,
#' @param washoutPeriod The mininum required continuous observation time prior to index
#' date for a person to be included in the cohort.
#' @param removeSubjectsWithPriorOutcome Remove subjects that have the outcome prior to the risk window start?
#' @param priorOutcomeLookback How many days should we look back when identifying prior outcomes?
#' @param requireTimeAtRisk Should subject without time at risk be removed?
#' @param minTimeAtRisk The minimum number of days at risk required to be included
#' @param riskWindowStart The start of the risk window (in days) relative to the index date (+
#' days of exposure if the \code{addExposureDaysToStart} parameter is
#' specified).
#' @param startAnchor The anchor point for the start of the risk window. Can be "cohort start" or "cohort end".
#' @param riskWindowEnd The end of the risk window (in days) relative to the index data (+
#' days of exposure if the \code{addExposureDaysToEnd} parameter is
#' specified).
#' @param endAnchor The anchor point for the end of the risk window. Can be "cohort start" or "cohort end".
#' @param restrictTarToCohortEnd If using a survival model and you want the time-at-risk to end at the cohort end date set this to T
#' @return
#' An object of type populationSettings containing all the settings required
#' for creating the study population
#' @examples
#' # Create study population settings with a washout period of 30 days and a
#' # risk window of 1 to 90 days
#' populationSettings <- createStudyPopulationSettings(washoutPeriod = 30,
#' riskWindowStart = 1,
#' riskWindowEnd = 90)
#' @export
createStudyPopulationSettings <- function(
binary = TRUE,
includeAllOutcomes = TRUE,
firstExposureOnly = FALSE,
washoutPeriod = 0,
removeSubjectsWithPriorOutcome = TRUE,
priorOutcomeLookback = 99999,
requireTimeAtRisk = TRUE,
minTimeAtRisk = 364,
riskWindowStart = 1,
startAnchor = "cohort start",
riskWindowEnd = 365,
endAnchor = "cohort start",
restrictTarToCohortEnd = FALSE) {
checkIsClass(binary, "logical")
checkNotNull(binary)
checkIsClass(includeAllOutcomes, "logical")
checkNotNull(includeAllOutcomes)
checkIsClass(firstExposureOnly, "logical")
checkNotNull(firstExposureOnly)
checkIsClass(washoutPeriod, c("numeric", "integer"))
checkNotNull(washoutPeriod)
checkHigherEqual(washoutPeriod, 0)
checkIsClass(removeSubjectsWithPriorOutcome, "logical")
checkNotNull(removeSubjectsWithPriorOutcome)
checkIsClass(priorOutcomeLookback, c("numeric", "integer"))
checkNotNull(priorOutcomeLookback)
checkHigherEqual(priorOutcomeLookback, 0)
checkIsClass(requireTimeAtRisk, "logical")
checkNotNull(requireTimeAtRisk)
if (requireTimeAtRisk) {
checkIsClass(minTimeAtRisk, c("numeric", "integer"))
checkNotNull(minTimeAtRisk)
checkHigherEqual(minTimeAtRisk, 0)
}
checkIsClass(riskWindowStart, c("numeric", "integer"))
checkNotNull(riskWindowStart)
checkIsClass(startAnchor, c("character"))
checkNotNull(startAnchor)
if (!startAnchor %in% c("cohort start", "cohort end")) {
stop("Incorrect startAnchor")
}
checkIsClass(riskWindowEnd, c("numeric", "integer"))
checkNotNull(riskWindowEnd)
checkIsClass(endAnchor, c("character"))
checkNotNull(endAnchor)
if (!endAnchor %in% c("cohort start", "cohort end")) {
stop("Incorrect endAnchor")
}
if (startAnchor == endAnchor) {
checkHigherEqual(riskWindowEnd, riskWindowStart)
}
checkIsClass(restrictTarToCohortEnd, "logical")
checkNotNull(restrictTarToCohortEnd)
if (requireTimeAtRisk) {
if (startAnchor == endAnchor) {
if (minTimeAtRisk > (riskWindowEnd - riskWindowStart)) {
warning("issue: minTimeAtRisk is greater than max possible time-at-risk")
}
}
}
result <- list(
binary = binary,
includeAllOutcomes = includeAllOutcomes,
firstExposureOnly = firstExposureOnly,
washoutPeriod = washoutPeriod,
removeSubjectsWithPriorOutcome = removeSubjectsWithPriorOutcome,
priorOutcomeLookback = priorOutcomeLookback,
requireTimeAtRisk = requireTimeAtRisk,
minTimeAtRisk = minTimeAtRisk,
riskWindowStart = riskWindowStart,
startAnchor = startAnchor,
riskWindowEnd = riskWindowEnd,
endAnchor = endAnchor,
restrictTarToCohortEnd = restrictTarToCohortEnd
)
class(result) <- "populationSettings"
return(result)
}
#' Create a study population
#'
#' @details
#' Create a study population by enforcing certain inclusion and exclusion criteria, defining
#' a risk window, and determining which outcomes fall inside the risk window.
#'
#' @param plpData An object of type \code{plpData} as generated using
#' \code{getplpData}.
#' @param outcomeId The ID of the outcome.
#' @param populationSettings An object of class populationSettings created using \code{createPopulationSettings}
#' @param population If specified, this population will be used as the starting point instead of the
#' cohorts in the \code{plpData} object.
#'
#' @return
#' A data frame specifying the study population. This data frame will have the following columns:
#' \describe{
#' \item{rowId}{A unique identifier for an exposure}
#' \item{subjectId}{The person ID of the subject}
#' \item{cohortStartdate}{The index date}
#' \item{outcomeCount}{The number of outcomes observed during the risk window}
#' \item{timeAtRisk}{The number of days in the risk window}
#' \item{survivalTime}{The number of days until either the outcome or the end of the risk window}
#' }
#' @examples
#' \donttest{ \dontshow{ # takes too long }
#' data("simulationProfile")
#' plpData <- simulatePlpData(simulationProfile, n = 100, seed = 42)
#' # Create study population, require time at risk of 30 days. The risk window is 1 to 90 days.
#' populationSettings <- createStudyPopulationSettings(requireTimeAtRisk = TRUE,
#' minTimeAtRisk = 30,
#' riskWindowStart = 1,
#' riskWindowEnd = 90)
#' population <- createStudyPopulation(plpData, outcomeId = 3, populationSettings)
#' }
#' @export
createStudyPopulation <- function(
plpData,
outcomeId = plpData$metaData$databaseDetails$outcomeIds[1],
populationSettings = createStudyPopulationSettings(),
population = NULL) {
start <- Sys.time()
checkIsClass(populationSettings, "populationSettings")
binary <- populationSettings$binary
includeAllOutcomes <- populationSettings$includeAllOutcomes
firstExposureOnly <- populationSettings$firstExposureOnly
washoutPeriod <- populationSettings$washoutPeriod
removeSubjectsWithPriorOutcome <- populationSettings$removeSubjectsWithPriorOutcome
priorOutcomeLookback <- populationSettings$priorOutcomeLookback
requireTimeAtRisk <- populationSettings$requireTimeAtRisk
minTimeAtRisk <- populationSettings$minTimeAtRisk
riskWindowStart <- populationSettings$riskWindowStart
startAnchor <- populationSettings$startAnchor
riskWindowEnd <- populationSettings$riskWindowEnd
endAnchor <- populationSettings$endAnchor
restrictTarToCohortEnd <- populationSettings$restrictTarToCohortEnd
# parameter checks
if (!inherits(x = plpData, what = c("plpData"))) {
ParallelLogger::logError("Check plpData format")
stop("Wrong plpData input")
}
ParallelLogger::logDebug(paste0("outcomeId: ", outcomeId))
checkNotNull(outcomeId)
ParallelLogger::logDebug(paste0("binary: ", binary))
ParallelLogger::logDebug(paste0("includeAllOutcomes: ", includeAllOutcomes))
ParallelLogger::logDebug(paste0("firstExposureOnly: ", firstExposureOnly))
ParallelLogger::logDebug(paste0("washoutPeriod: ", washoutPeriod))
ParallelLogger::logDebug(paste0("removeSubjectsWithPriorOutcome: ", removeSubjectsWithPriorOutcome))
ParallelLogger::logDebug(paste0("priorOutcomeLookback: ", priorOutcomeLookback))
ParallelLogger::logDebug(paste0("requireTimeAtRisk: ", requireTimeAtRisk))
ParallelLogger::logDebug(paste0("minTimeAtRisk: ", minTimeAtRisk))
ParallelLogger::logDebug(paste0("restrictTarToCohortEnd: ", restrictTarToCohortEnd))
ParallelLogger::logDebug(paste0("riskWindowStart: ", riskWindowStart))
ParallelLogger::logDebug(paste0("startAnchor: ", startAnchor))
ParallelLogger::logDebug(paste0("riskWindowEnd: ", riskWindowEnd))
ParallelLogger::logDebug(paste0("endAnchor: ", endAnchor))
ParallelLogger::logDebug(paste0("restrictTarToCohortEnd: ", restrictTarToCohortEnd))
if (is.null(population)) {
population <- plpData$cohorts
} else {
population <- plpData$cohorts %>%
dplyr::filter(.data$rowId %in% (population %>% dplyr::pull(.data$rowId)))
}
# save the metadata (should have the ?targetId, outcomeId, plpDataSettings and population settings)
metaData <- attr(population, "metaData")
metaData$restrictPlpDataSettings <- plpData$metaData$restrictPlpDataSettings
metaData$outcomeId <- outcomeId
metaData$populationSettings <- populationSettings # this will overwrite an existing setting
# set the existing attrition
if (is.null(metaData$attrition)) {
metaData$attrition <- attr(plpData$cohorts, "metaData")$attrition
}
if (!is.null(metaData$attrition)) {
metaData$attrition <- data.frame(
outcomeId = metaData$attrition$outcomeId,
description = metaData$attrition$description,
targetCount = metaData$attrition$targetCount,
uniquePeople = metaData$attrition$uniquePeople,
outcomes = metaData$attrition$outcomes
)
if (sum(metaData$attrition$outcomeId == outcomeId) > 0) {
metaData$attrition <- metaData$attrition[metaData$attrition$outcomeId == outcomeId, ]
} else {
metaData$attrition <- NULL
}
}
# ADD TAR
oId <- outcomeId
population <- population %>%
dplyr::mutate(
startAnchor = startAnchor, startDay = riskWindowStart,
endAnchor = endAnchor, endDay = riskWindowEnd
) %>%
dplyr::mutate(
tarStart = ifelse(.data$startAnchor == "cohort start", .data$startDay, .data$startDay + .data$daysToCohortEnd),
tarEnd = ifelse(.data$endAnchor == "cohort start", .data$endDay, .data$endDay + .data$daysToCohortEnd)
) %>%
dplyr::mutate(tarEnd = ifelse(.data$tarEnd > .data$daysToObsEnd, .data$daysToObsEnd, .data$tarEnd))
# censor at cohortEndDate:
if (max(population$daysToCohortEnd) > 0 && restrictTarToCohortEnd) {
ParallelLogger::logInfo("Restricting tarEnd to end of target cohort")
population <- population %>% dplyr::mutate(tarEnd = ifelse(.data$tarEnd > .data$daysToCohortEnd, .data$daysToCohortEnd, .data$tarEnd))
}
# get the outcomes during TAR
outcomeTAR <- plpData$outcomes %>%
dplyr::filter(.data$outcomeId == get("oId")) %>%
dplyr::inner_join(population, by = "rowId") %>%
dplyr::select("rowId", "daysToEvent", "tarStart", "tarEnd") %>%
dplyr::filter(.data$daysToEvent >= .data$tarStart & .data$daysToEvent <= .data$tarEnd)
# prevent warnings when no results left
if (nrow(as.data.frame(outcomeTAR)) > 0) {
outcomeTAR <- outcomeTAR %>%
dplyr::group_by(.data$rowId) %>%
dplyr::summarise(
first = min(.data$daysToEvent),
ocount = length(unique(.data$daysToEvent))
) %>%
dplyr::select("rowId", "first", "ocount")
} else {
outcomeTAR <- outcomeTAR %>%
dplyr::mutate(first = 0, ocount = 0) %>%
dplyr::select("rowId", "first", "ocount")
}
population <- population %>%
dplyr::left_join(outcomeTAR, by = "rowId")
# get the initial row
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = "Initial plpData cohort or population",
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
if (firstExposureOnly) {
ParallelLogger::logTrace(paste("Restricting to first exposure"))
if (nrow(population) > dplyr::n_distinct(population$subjectId)) {
population <- population %>%
dplyr::arrange(.data$subjectId, .data$cohortStartDate) %>%
dplyr::group_by(.data$subjectId) %>%
dplyr::filter(dplyr::row_number(.data$subjectId) == 1)
}
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = "First Exposure",
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
}
if (washoutPeriod) {
ParallelLogger::logTrace(paste("Requiring", washoutPeriod, "days of observation prior index date"))
msg <- paste("At least", washoutPeriod, "days of observation prior")
population <- population %>%
dplyr::mutate(washoutPeriod = washoutPeriod) %>%
dplyr::filter(.data$daysFromObsStart >= .data$washoutPeriod)
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = msg,
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
}
if (removeSubjectsWithPriorOutcome) {
ParallelLogger::logTrace("Removing subjects with prior outcomes (if any)")
# get the outcomes during TAR
outcomeBefore <- plpData$outcomes %>%
dplyr::filter(outcomeId == get("oId")) %>%
dplyr::inner_join(population, by = "rowId") %>%
dplyr::select("rowId", "daysToEvent", "tarStart") %>%
dplyr::filter(.data$daysToEvent < .data$tarStart & .data$daysToEvent > -get("priorOutcomeLookback"))
if (nrow(as.data.frame(outcomeBefore)) > 0) {
outcomeBefore %>%
dplyr::group_by(.data$rowId) %>%
dplyr::summarise(first = min(.data$daysToEvent)) %>%
dplyr::select("rowId")
}
population <- population %>%
dplyr::filter(!.data$rowId %in% outcomeBefore$rowId)
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = "No prior outcome",
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
}
if (requireTimeAtRisk) {
if (includeAllOutcomes) {
ParallelLogger::logTrace("Removing non outcome subjects with insufficient time at risk (if any)")
population <- population %>%
dplyr::filter(!is.na(.data$first) | .data$tarEnd >= .data$tarStart + minTimeAtRisk)
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = "Removing non-outcome subjects with insufficient time at risk (if any)",
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
} else {
ParallelLogger::logTrace("Removing subjects with insufficient time at risk (if any)")
population <- population %>%
dplyr::filter(.data$tarEnd >= .data$tarStart + minTimeAtRisk)
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = "Removing subjects with insufficient time at risk (if any)",
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
}
} else {
# remve any patients with negative timeAtRisk
ParallelLogger::logTrace("Removing subjects with no time at risk (if any)")
population <- population %>%
dplyr::filter(.data$tarEnd >= .data$tarStart)
attrRow <- population %>%
dplyr::group_by() %>%
dplyr::summarise(
outcomeId = get("oId"),
description = "Removing subjects with no time at risk (if any))",
targetCount = length(.data$rowId),
uniquePeople = length(unique(.data$subjectId)),
outcomes = sum(!is.na(.data$first))
)
metaData$attrition <- rbind(metaData$attrition, attrRow)
}
# now add columns to pop
if (binary) {
ParallelLogger::logInfo("Outcome is 0 or 1")
population <- population %>%
dplyr::mutate(outcomeCount = ifelse(is.na(.data$ocount), 0, 1))
} else {
ParallelLogger::logTrace("Outcome is count")
population <- population %>%
dplyr::mutate(outcomeCount = ifelse(is.na(.data$ocount), 0, .data$ocount))
}
population <- population %>%
dplyr::mutate(
timeAtRisk = .data$tarEnd - .data$tarStart + 1,
survivalTime = ifelse(.data$outcomeCount == 0, .data$tarEnd - .data$tarStart + 1, .data$first - .data$tarStart + 1),
daysToEvent = .data$first
) %>%
dplyr::select(
"rowId", "subjectId", "targetId", "cohortStartDate", "daysFromObsStart",
"daysToCohortEnd", "daysToObsEnd", "ageYear", "gender",
"outcomeCount", "timeAtRisk", "daysToEvent", "survivalTime"
)
# check outcome still there
if (sum(!is.na(population$daysToEvent)) == 0) {
ParallelLogger::logWarn("No outcomes left...")
return(NULL)
}
ParallelLogger::logInfo(
"Population created with: ", nrow(population),
" observations, ", length(unique(population$subjectId)),
" unique subjects and ", sum(population$outcomeCount), " outcomes"
)
population <- as.data.frame(population)
attr(population, "metaData") <- metaData
delta <- Sys.time() - start
ParallelLogger::logInfo("Population created in ", signif(delta, 3), " ", attr(delta, "units"))
return(population)
}
getCounts <- function(population, description = "") {
persons <- length(unique(population$subjectId))
targets <- nrow(population)
counts <- data.frame(
description = description,
targetCount = targets,
uniquePeople = persons
)
return(counts)
}
getCounts2 <- function(cohort, outcomes, description = "") {
persons <- length(unique(cohort$subjectId))
targets <- nrow(cohort)
outcomes <- stats::aggregate(cbind(count = outcomeId) ~ outcomeId,
data = outcomes,
FUN = function(x) {
NROW(x)
}
)
counts <- data.frame(
outcomeId = outcomes$outcomeId,
description = description,
targetCount = targets,
uniquePeople = persons,
outcomes = outcomes$count
)
return(counts)
}