Skip to content

Instantly share code, notes, and snippets.

@syadlowsky
Created October 10, 2019 01:42
Show Gist options
  • Save syadlowsky/2595169887488103d19a8699eeda882a to your computer and use it in GitHub Desktop.
Save syadlowsky/2595169887488103d19a8699eeda882a to your computer and use it in GitHub Desktop.
# Idea thanks to https://scottclowe.com/2016-03-19-stratified-regression-partitions/
# Adapted for right censored survival outcomes by applying the above procedure
# separately for censored and uncensored observations.
# Copyright 2019 Steve Yadlowsky
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
library(dplyr)
partition_sorted_data_frame = function(frame, k) {
n = nrow(frame)
left_overs = n %% k
fold_order = do.call(c, lapply(1:n %/% k,
function(x) {sample.int(k, k)}))
return(c(fold_order, sample.int(k, left_overs)))
}
partition_survival_data = function(surv_obj, k) {
survival_frame = data.frame(t_ = surv_obj[,1],
e_ = surv_obj[,2],
index=1:nrow(surv_obj))
censored_obs = survival_frame %>% dplyr::filter(e_ == 0)
if (nrow(censored_obs) > 0) {
censored_obs = censored_obs %>% dplyr::arrange(t_)
censored_fold_ids = partition_sorted_data_frame(censored_obs,k)
censored_indices = censored_obs %>% pull(index)
} else {
censored_fold_ids = NULL
censored_indices = NULL
}
event_obs = survival_frame %>% dplyr::filter(e_ == 1)
if (nrow(event_obs) > 0) {
event_obs = event_obs %>% dplyr::arrange(t_)
event_fold_ids = partition_sorted_data_frame(event_obs, k)
event_indices = event_obs %>% pull(index)
} else {
event_fold_ids = NULL
event_indices = NULL
}
fold_order = c(censored_fold_ids,
event_fold_ids)
indices = c(censored_indices,
event_indices)
return(fold_order[order(indices)])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment