Last active
August 10, 2020 13:07
-
-
Save danlewer/8466ecc5dea046c288bcec6b64ea353d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 'a' is a vector | |
# 'vals' is a vector | |
# returns a vector of same lengths as 'a' showing the last value in 'a' equal to any value in 'vals' | |
# 'fill' is the value given if none of the values in 'vals' has yet occurred in 'a' | |
# 'excl' is a vector specifying values of 'vals' that are to be excluded. Best used when vals is not specified (and defaults to unique(a)) | |
last_status <- function(a, vals = unique(a), excl = NA, fill = NA) { | |
if (!is.na(excl)) {vals <- setdiff(vals, excl)} | |
i <- a %in% vals | |
j <- a[i][cumsum(i)] | |
c(rep(fill, length(a) - length(j)), j) | |
} | |
# example: use a sequence of prescribing events to determine whether a patient had a current prescription of citalopram at each time | |
pharma_history <- c('eucerin', 'benazepril_start', 'aspirin', 'aspirin', 'citalopram_start', NA, 'aspirin', 'eucerin', NA, 'citalopram_end', '%%%%', NA) | |
last_status(pharma_history, c('citalopram_start', 'citalopram_end')) # 'citalopram_start' indicates current prescription |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment