I could use some help with a custom function that I've been working on that takes the parallel minima of a vector of variables (all date of diagnosis variables, with dx dates for cases and NA for noncases).
I want to create 2 variables:
- {prefix}flag1 sets all nonmissing values to 1 and all missing values to 0
- {prefix}flag2 finds the earliest possible date of the vector of variables for each observation/ row.
I've been able to generate a function using the invoke() wrapper; however, since the rlang function is being depreciated, I'm trying to execute the same function using exec() or inject() instead.
The actual dataset has 100+ columns, but I am supplying a minimally reproducible example below.
# load libs
library(tidyverse)
library(lubridate)
rdate <- function(x,
min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
sort = TRUE) {
dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace = TRUE)
if (sort == TRUE) {
sort(dates)
} else {
dates
}
}
# set seed for reproducibility
set.seed(42)
# generating ds of random dates
date_ds <- data.frame(v.ar1 = rdate(15),
var_2 = rdate(15),
random3 = rdate(15),
v4= rdate(15),
v__5 = rdate(15),
variable6 = rdate(15),
dates7 = rdate(15)) %>%
# remove some observations
mutate(var_2 = as_date(ifelse(var_2 < dates7, var_2, NA)),
variable6 = as_date(ifelse(variable6 <= v__5, variable6, NA)),
v4 = as_date(ifelse(v4 > v.ar1, v4, NA)),
)
# vector of names
varnames <- names(date_ds)
# function
collapse_phenos <- function(varvector, prefix){
outds <- date_ds %>%
mutate(!!paste0(prefix,"flag1") := +(rowSums(!is.na(select(., all_of(varvector)))) > 0),
!!paste0(prefix,"flag2") := invoke(pmin, c(across(all_of(varvector)), na.rm = TRUE)))
return(outds)
}
# return ds
result <- collapse_phenos(varvector = varnames, prefix = "")
Any help would be appreciated! A tidyverse solution would be preferable.