not pretty but it works.
library(tidyverse)
library(glue)
data <- tibble::tribble(
~id, ~measurename_1, ~measurename_2, ~measurename_3, ~measure_1, ~measure_2, ~measure_3, ~date_1, ~date_2, ~date_3, ~datetarget,
1, "height", "height", "length", 10, 40, 19, "2001-02-11", "2001-02-11", "2006-06-05", "2001-02-21",
2, "length", "length", "height", 40, 2, 719, "2005-04-04", "2006-06-05", "2014-04-04", "2006-03-23",
3, "length", "height", "length", 41, 13, 32, "2001-02-11", "2004-03-12", "2018-12-31", "2019-01-10",
4, "height", "length", "height", 6, 400, 2, "2010-05-02", "2013-01-19", "2013-10-29", "2013-01-29",
5, "length", "height", "height", 100, 12, 129, "2019-11-20", "2019-11-20", "2019-07-30", "2019-11-30"
) %>% mutate(across(starts_with("date"),
as.Date)) %>% as.data.frame()
# So if "date_x = datetarget - 10" and "measurename_x = length"
# then a new column named "date-10" will be added showing the observation from measure_x.
mymake <- function(days,nums){
walk(
nums,
~ {
data[, glue("d_{days}_{.x}")] <<-
ifelse(data[, glue("date_{.x}")] == data[, "datetarget"] - days &
data[, glue("measurename_{.x}")] == "length",
data[, glue("measure_{.x}")], NA
)
}
)
data
}
mymake(10,1:3)
#coalescer
mycoal <- function(name,nums){
data[, glue("{name}")] <<- eval(str2expression(
glue('coalesce({paste0("data$",name,"_",nums,collapse = ",")})')
))
eval(str2expression(paste0("data$",name,"_",nums,"<<- NULL",collapse = ";")
))
data
}
mycoal("d_10",1:3)