How adjust code functionality to specifications using data.table function

I would like to change the approach to generating Output. Is it possible to use the data.table function for this case below? If yes, could you help me adjust? I have inserted an example below of the calculation that is done.

library(dplyr)
library(tidyverse)
library(lubridate)


df1 <- structure(list(date1 = c("2021-06-28"), 
                      date2 = c("2021-06-30"), 
                      Category = c("FDE"), 
                      Week = c("Wednesday"), 
                      DR1 = c(4), DRM001 = c(4), DRM002 = c(2), 
                      DRM003 = c(9), DRM004 = c(5), DRM005 = c(5), 
                      DRM006 = c(2),DRM007 = c(1),
                      coef = c(8)), class = "data.frame", row.names = c(NA, -1L))


Output<-df1 %>% 
  mutate(across(starts_with("DR"), ~ coef - .),
         across(contains("date"), ymd),
         datedif = parse_number(as.character(date2-date1))
  ) %>% 
  rename_with(~str_replace(.,'(?<=[A-Z])0+(?=.)', ""),starts_with('DR')) %>% 
  rowwise %>%
  mutate(Result = if (str_c('DRM', datedif) %in% names(.)) get(str_c('DRM', datedif)) else coef) %>%
  ungroup() %>% 
  select(coef, Result)%>%data.frame()

> Output
  coef Result
1    8      6

For example: See that coef is 8 and the difference between date1 and date2 is 2, so Result is equal to coef - DRM2. If the difference between dates was 3 then it would be Result = coef - DRM3

   date1      date2     Category  Week     DR1 DRM1 DRM2 DRM3 DRM4 DRM5 DRM6 DRM7 coef datedif
1 2021-06-28 2021-06-30  FDE    Wednesday   4    4    6   -1    3    3    6    7    8       2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.